0

The first time I asked a question here, I wrote in my review material that "the upper transformation object can access the overridden static method in the subclass (access to the value in the parent class)", I wrote a code, run The result is indeed this, but I don't know why?

class Father{
    Father(){
        System.out.println("Father");
    }
    void test1(){
        System.out.println("Father test1");
    }
    static void test2() {
        System.out.println("Father test2");
    }
}
class Son extends Father{
    Son(){
        System.out.println("Son");
    }
    void test1(){
        System.out.println("Son test1");
    }
    static void test2() {
        System.out.println("Son test2");
    }
}
public class FatherSon {
    public static void main(String args[]){
        Father f2=new Son();
        f2.test1();
        f2.test2();
    }
}

operation result:

Father
Son
Son test1
Father test2
  • 5
    Does this answer your question? [Can I override and overload static methods in Java?](https://stackoverflow.com/questions/2475259/can-i-override-and-overload-static-methods-in-java) – fuggerjaki61 Jun 30 '20 at 07:10
  • 2
    *"overridden static method"* – Static methods are not susceptible for overriding. – MC Emperor Jun 30 '20 at 07:11
  • Why the upper cast object cannot access the overridden static method in the subclass ?about"Son test1"this result. – TheLittleCute Jun 30 '20 at 07:12
  • It was perhaps a design failure in early Java to allow static methods to be called via object references. Thus, always use the class to invoke static methods: `Father.test2()` – Gyro Gearless Jun 30 '20 at 07:25

2 Answers2

1

You can not override static method in Java, though you can declare a method with the same signature in a subclass. It won't be overridden in the exact sense, instead, that is called method hiding.


More explanation:

Non-static methods can be overridden since they are resolved using dynamic binding at run time.

Whereas static methods belong to the class and not the object of the class.Static methods can only be overloaded since they are resolved using static binding by compiler at compile time.

Abhinaba Chakraborty
  • 3,488
  • 2
  • 16
  • 37
0

You use :

Father f2=new Son();

Because test2() is a static method the compiler will use the declared type to select the good function to call, here he choose the test2() of Father.

But if you declare :

Son f2=new Son();

The compiler will use the test2() of Son class.