-1
public class Base {
    private static boolean goo = true;
    protected static boolean foo() {
          goo = !goo;
          return goo;
    }

    public String bar = "Base:" + foo();

    public static void main(String[] args) {
         Base base = new Sub();
         System.out.println("Base:"+ base.foo());
    }
}

public class Sub extends Base {
    public String bar = "Sub:" + foo();
    protected static boolean foo() {
        return false;
    }
}

Why the output is "Base: true"? foo() seems to be an overriding method so dynamic type is Sub, than why the return output isn't "false", and also the field of Base has a string, shouldn't there be its output?

Misha
  • 27,433
  • 6
  • 62
  • 78
student
  • 25
  • 6

3 Answers3

1

In java, you can not override the static methods, If you redefine that static method of super class method in sub class then it becomes method over-written(method hiding), not overriding.

In your example, you are invoking it with the super class ref(base) so the super class method only invoked not the sub class method. so the output is "Base: true"

If you change it with non static method then the sub class method will be executed.

Here the rule is: super class ref and sub class object will work for non static methods.

surya prakash
  • 49
  • 1
  • 5
0

Method overriding is used to override the behaviour of an object for a subclass and is not applicable for static methods. There is no reason to support this feature for static methods. Moreover, you don't need to create an object to access a static method. You can simply refer it by its name[foo()] or use classname as a prefix[eg: Sub.foo()].

As far as why true is being returned in an output is concerned , this is because you have already used below statement in your class , which invokes foo() method

public String bar = "Base:" + foo();

Since goo is a static variable, only one instance of this variable is maintained for this class . And on execution of above statement , the value of goo changes to false(goo=!goo,goo initially being true).

Later on , when you use base.foo() , foo() of base class will be executed [As method overriding not applicable for static methods and Base class reference is being used] which again reverts the value of goo making it true.

Shubhi224
  • 104
  • 6
0

When you are dealing with the word "static" in terms of a method or a variable, it refers that the method or a variable belong to the "class" and not its object.

When there is no object, there is no overriding.

In your class Base, you declared the main() method, in which you wrote the following statements.

Base base = new Sub();
System.out.println("Base:"+ base.foo());

Now, the reference variable type is Base and the object type is Sub. Since foo() is a static method it belongs to the class of which the reference variable is declared (i.e. Base). Therefore, foo method of class Base is called.

Monis
  • 918
  • 7
  • 17