Static method are not overriden ?

Hi,
as I try to understand java in depth, I come back with this simple question:
public class hiddenVar1 {
boolean aVariable=true;
public static void main (String [] args) {
System.out.println("Hello");
public class hiddenVar2 extends hiddenVar1 {
boolean aVariable;
public hiddenVar2() {
aMethod();
void aMethod() {
aVariable = false;
System.out.println(aVariable);
System.out.println(super.aVariable);
public static void main (String [] args) {
new hiddenVar2();
hiddenVar1.main(new String[2]);
The result is :
false
true
Hello
Conclusion:
the main static method of hiddenVar1 as not been overrided by the main static method in hiddenVar2.
So inheritance does not apply for static method ?
Any explanation ?
Thank's.
John

Firstly i think there should not be two public classes in only one file it gives compile time error.
Secondly the output is correct.
Static methods cannot be overriden because it will get initialize when u create instance of the class so u r calling
-- new hiddenVar2();
so it calls the constructor in that respective method is called.
And the second line is calling the super class so it calls the main method of that class and prints "hello"
hiddenVar1.main(new String[2]);

Similar Messages

  • What a static method cannot be overriden?

    Parent class
    public class Person {
       private String surname;
       private String firstName;
       private String secondName;
       public Person(String surname,
                     String firstName,
                     String secondName) {
            this.surname = surname;
            this.firstName = firstName;
            this.secondName = secondName;
       public static void test() { ; }
    }Sub class
    public class Member extends Person {
         private int membershipNumber;
                     public Member(String surname,
                      String firstName,
                      String secondName,
                      int membershipNumber) {
              super(surname, firstName, secondName);
              this.membershipNumber = membershipNumber;
         public String toString() {
              return membershipNumber + "-" + super.toString();
         public void test() { System.out.println("test") ; }
    }And I got compilation error :
    H:\java\wshp2>javac *.java
    Member.java:20: test() in Member cannot override test() in Person; overridden me
    thod is static
    public void test() { System.out.println("test") ; }
    ^
    1 error
    H:\java\wshp2>pause
    Since static method and the overriding method are going to be used differently (in different ways), why it can't be allowed?
    Static method is a Class method whereas the overriding method is a instance method, they can be distinguished. What is the reason behind this?
    Please enlighten me.
    Thanks

    Are final method bound at compile-time?Basically when a method is "bound" cannot be used to explain the behaviour of methods in Java. It's the other way around. It's the characteristics of a method that decides when it can be "bound". But that's an implementation issue and not part of the language itself.
    A static method cannot be overriden because it's not meant to be overridden. It's against the semantics of a static method to be overridden. Also if you declare a method final you decide that you don't want it to be overriden. In both cases, based on this non-overriding restriction, the compiler can decide when to "bind" the method.

  • Why global var can be initialized with a static method and not by other static global var declared after its usage

    Take this:
    class test
    static int i=j;
    static int j=10;
    this will give illegal forward reference ....
    but this will compile successfully ..
    class test
    static int i=test1();
    static test1()
    return 20;
    plz assume we have main method in both cases ..
    java would be loading all static members first and would be assigning default values .. and then will be running all the initializers from to bottom ..
    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Plz help.
    Thanks
    Abhishek Roshan

    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Because the implementors of Java intentionally chose to do it that way.
    There are TWO stages to the process: preparation (which occurs first) and initialization.
    See the Java Language Spec section 12.4.1 'When Initialization Occurs
    The intent is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
    Note the clause beginning 'may not refer to class variables'. And the authors give the reason for that restriction in the last sentence: detect circular initializations.
    Then if you check that referenced section 8.3.2.3 you will find this
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3
    8.3.2.3. Restrictions on the use of Fields during Initialization
    The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
      The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
      The usage is not on the left hand side of an assignment.
      The usage is via a simple name.
      C is the innermost class or interface enclosing the usage.
    When a method is used (your example 2) no circular initialization can occur because methods are not 'initialized'.

  • Why addcomponent and removecomponent method are not in component class,

    Hi,
    why addcomponent and removecomponent method are not in component oand component class,
    Thank you

    java.awt.Container has the appropriate add and remove methods:
    http://java.sun.com/javase/6/docs/api/java/awt/Container.html
    If that seems odd to you, you need to think about the Composite Pattern:
    http://en.wikipedia.org/wiki/Composite_pattern
    [url #" style="display: block; background-image: url('http://upload.wikimedia.org/wikipedia/en/1/13/Compositepattern.png'); width: 406px; height: 271px] 

  • Difference between calling static method and not static method?

    Hi,
    Suppose i want to write a util method, and many class might call this method. what is better? writing the method as static method or not static method. what is the difference. what is the advantace in what case?

    writing the method as static method or not static
    method. what is the difference.The difference is the one between static and non-static. Any tutorial or the JLs will clarify the difference, no need to repeat it here.
    what is the advantace in what case?It's usually not like you have much of a choice. If you need access to an instance's attributes, you can't make it static. Otherwise, make it static.

  • Static method or not static method

    I have a simple class, ClassA, with no shared class variables, and has only one static method only:
    class ClassA {
    public static void doIO (args) {
    try {
    //very time consuming I/O task
    catach (Exceptions e) { 
    //try to resolve the problem
    This doIO method will be called simultaneously from different objects.
    My questions are:
    1) Would this static method approach cause any robustness, efficiency problem? Or, should I change the method into a non-static method, and create a new instance of ClassA every time?
    2) If there are 20 threads call ClassA.doIO(args) at the same time, would the method be executed in parallel or queued?
    Many thanks.
    java9394

    Using a static method makes this implementation as efficient as possible. Since the class has no instance variables, there is no benefit, to either making it non-static, or creating multiple instances. If you have 20 threads calling it, they will run concurrently. So, if you do not like this behavior, the method can be declared both static, and synchronized.

  • Why to use Interface if methods are not implemented??

    Hello,
    I am having a problem to clearify as, why to use the interfaces which defines only methods and no implementation??
    When a class implements an interface the methods are implemented by the class itself, don't you think that the same functionality can be achieved if the class defined the method itself...
    The why to use interfaces, just that the same method name can be used by many classes or some other reasons..

    did you google on that? There is lots of information I am sure explaining why you code to an interface defined type rather than a class defined type.
    However, fundamentally you are correct, classes define their own type. The idea is that you use an interface because it allows you to have more than one implementation. Plus you can more easily change the structure of your program if you later wish if you did not use the class type directly.
    You get better answers if you ask in the Patterns forum below.

  • Static methods, or not...

    Ok, i've got a class with around 50 or so methods in it. im going to have around a hundred of these classes going at once. my question is: should i make all the methods static, and then pass in an instance of a class to work on? would that use less memory, or be beneficial in any way? im probably completely wrong, but i wanted to check anwyays, just in case..
    so, for example
    public void stuff(){
    x++;
    turning into
    public void stuff(SomeClass target){
    target.x++;
    }

    For each method there is (generally) one and only one implementation loaded into memory. Having 10 thousand instances of a class does not create copies 10 thousand copies of the methods. No, using static methods would be a waste of your energy and probably be a rather poor design.
    Chuck

  • Set Methods are not running

    I am writing my first jsp. I have a bean that I am wanting to use and my understanding is that if I put the following commands in, that all the set methods for my properties will run in the bean automatically as long as the names of the properties are the same as those on the form.
    <jsp:useBean id="MedicalBean" class="Project5.MedicalReimbursementRecord" scope="session"/>
    <jsp:setProperty name="MedicalBean" property="*"/>
    The form has a number of textboxes, each text box has a name of one of the properties in my bean. I put display in my bean and I know that it is never running any of the "set" methods for any of the properties. I know that it is indeed getting into my bean, as I have displayed which indicate that methods that I request are indeed running.
    I have not "ACTION" parameter on the FORM, but I have looked at the examples in Tomcat and they have forms which do not have an "Action". I don't think this is a problem, but maybe I am wrong about that. If I put in the statement of:
    <jsp:setProperty name="MedicalBean" property="GrpAcctNbr"/>
    Then I get the error "Cannot find any information on property 'GrpAcctMbr' in a bean of type 'Project5.MedicalReimbursementRecord'"
    So there must be something wrong with my setProperty statement, but what is it?
    Thanks in advance for your assistance.

    Can you show the relevant JSP code and set/get methods in the bean?
    Sometimes this error is caused by capitalization. e.g. a request param of "myName" calls setMyName(). Also, your bean must have a no arguments constructor.
    Also, if you don't specify an action,the form submits to the current URL so you should be ok. Are you sure that the JSP runs when the user submits the form?

  • CL_ABAP_DATFM methods are not working in IDES system

    Hi Experts,
    i am trying to execute some date related methods, here example the method  conv_date_ext_to_int  which converts external date format to internal format.
    this method is working properly in the client systems other than IDES system(client:800) , but not showing the class and methods in IDES system,
    so i just want to know why it is not showing and working in IDES system, please reply me.
    Thanks & Regards,
    Sridhar Allenki

    I will say it again - Roles in ABAP system appear as groups in portal.
    Now, the task you are probably missing is to assign the portal role to the appropriate groups (ABAP roles) in your portal.
    In your production portal - check the Portal Role to group (ABAP role) assignment and do the same in your DEV system.
    You can go to user administration in portal and search for the group and look for assigned roles.
    Thanks,
    Shanti

  • I dont know what to do!!! I pulled out my headphones and then saw that my sound was not working correctly. I was horrified to find a piece of the headphone never came out. I have heard how much it costs to repair and the other methods are not working.

    Please help, i am so scared that i will never get my laptop back the way it was.

    "the other methods aren't working"
    Well, what other methods have you tried that didn't work?  Frankly, your post reads as a hoax, but I have some extra time on my hands, and an idea.  Make an appointment with the Apple Genius at your local Apple store.  You could also bring your MBP to an AASP.  Regardless, either one should be able to remove the bottom cover, and use a plastic thingy (dang, what is that tool called?) to push out the offending bit.

  • Code compiles only when static methods are defined in a certain order

    CC: Sun C++ 5.9 SunOS_i386 Patch 124864-10 fails to compile the code below with
    "/tmp/notagain.cc", line 9: Error: static X::decode<X::T>() already had a body defined.
    "/tmp/notagain.cc", line 13: Error: Cannot use int* to initialize double*.
    struct X
        static int* decode(int Val);
        static int* decode();
        template<typename T> static T* decode() { return new T; }
    int* X::decode(int t) { return new int(t); }
    int* X::decode() { return new int; }
    int main() {
            int* pi = X::decode();
            double* pd = X::decode<double>();
            return 0;
    }It actually manages to compile it if the struct X is defined slightly differently:
    struct X
        static int* decode(int Val);
        template<typename T> static T* decode() { return new T; }
        static int* decode();
    int* X::decode(int t) { return new int(t); }
    int* X::decode() { return new int; }
    int main() {
            int* pi = X::decode();
            double* pd = X::decode<double>();
            return 0;
    }None of this happens with g++ or Intel C++.

    Thanks for filing the bug report. It has been assigned CR 6935439, and should be visible at [http://bugs.sun.com] in a day or two.

  • Why ejbActivate and ejbpassivate methods are not in the stateless bean

    please give me clearly

    You can translate "activate" and "passivate" as follows:
    activate means "please fetch the last state for this stateful session bean from the persistent store"
    passivate means "the container is going to unload this stateful session bean from memory, so please persist its state in the persistent store"
    Neither of those statements apply to stateless session beans, because they're stateless. There's nothing to persist. One SLSB is as good as another for servicing a request. They don't care who their last client was.
    %

  • How to determine the Class of a static methods class?

    hi,
    is there a way to get the code below to output
    foo() called on One.class
    foo() called on Two.classthanks,
    asjf
    public class Two extends One {
       public static void main(String [] arg) {
          One.foo(); // should say "foo() called on One.class"
          Two.foo(); // should say "foo() called on Two.class"
    class One {
       public static final void foo() {
          System.out.println("foo() called on "/*+something.getClass()*/);
    }

    - One.class won't resolve to Two.class when the static
    method is called via the class TwoThat's because static methods are not polymorphic. They cannot be overridden. For example try this:
    public class Two extends One {
       public static void main(String [] arg) {
          One.foo(); // should say "foo() called on One.class"
          Two.foo(); // should say "foo() called on Two.class"
          One one = new Two();
          one.foo();
          ((Two) one).foo();
       public static void foo() {
          System.out.println("foo() called on Two");
    class One {
       public static void foo() {
          System.out.println("foo() called on One");
    }

  • Find the Class Name in a static method

    Hi All,
    I am trying to find the class name inside the static main method. I want to write one main method that loads an instance of the class. Other folks have suggested tricks with the security manager or creating an Exception to look at the stack trace, but these methods don�t reflect the inheritance. I want SUBCLASSES to be able to run from the command line using the inherited main method.
    public static void main(String args[]){
          JPanel thisJPanel = (JPanel) Class.forName(????).newInstance();
    }Any Ideas

    I want
    SUBCLASSES to be able to run from the command line
    using the inherited main method.Someone pointed this out already but more directly, static methods are not inherited.
    The behavior you desire ca be achieved using the Factory pattern.
    The idea of being able to subclass an application is a little bizarre. Why don't you just do something like this:
    public static void main(String[] args){
        // check that there is at least one parameter 
        JPanel thisJPanel = (JPanel) Class.forName(args[0]).newInstance();
    }

Maybe you are looking for

  • Why is it that when iam trying to play movie in my iPad with netflix, it kept on shutting off?

    What is it with Netflix and IPad that I have to open over and over again b/c it kept on shutting it off when trying to select movies from it's selection. It is sooo frustrating! That is the main reason why I purchased this IPad in the first place. Is

  • Newbie: easiest way to see home webcam view from work?

    Hi, My Imac at home has the usual built-in isight camera, and I'm wanting to somehow set it up so that when I'm at work I can get my missus and our new baby to sit in front of it and I can see them. I don't have a webcam at work, so it would be a one

  • Problem text additional fields Query ad-hoc

    Dear All, We created a query using an additional field in the structure created P0001_AF. The fact is that our field has an associated text, which indicates how the output of our query, but the text always appears empty. The field has duly informed t

  • Oracle Reports Java API link Error

    The Oracle Reports Java API link on the Oracle Reports page produces an error. http://www.oracle.com/technology/products/reports/htdocs/getstart/docs/index.html

  • Satellite A500-1G0 - cannot update monitor driver

    I've installed standard nvidia driver http://support1.toshiba-tro.de/tedd-files2/0/display-20100608161152.zip , but display show me standar PnP device with microsoft standard drivers and 60hz frequency Win 7 home. I think there should be original dri