+ 3

About static method in JAVA

There is a question in playground. Method in child class must be marked as static if it is marked as static in the parent class(method hiding). The answer is TRUE. But in my memory,I learn that static method CAN'T be Override... Could someone help me lift the confusion? ~Thank you~

3rd Sep 2017, 3:49 AM
同學說他喜歡上課可是他沒來
同學說他喜歡上課可是他沒來 - avatar
2 Respostas
+ 6
In order for a method to be "overridden" it must belong to an instance of a class. Static methods belong to the class itself and an instance of the class is not needed in order to call that method. In order to redefine a static method in a child class it must also be static. If you don't make the child classes method static then you are attempting to override it which you cannot do. public class B extends A { /*public void sayHello() { System.out.println("Hello B"); }*/ public static void sayHello() { System.out.println("Hello B"); } } public class A { public static void sayHello() { System.out.println("Hello A"); } } public class Program { public static void main(String[] args) { A.sayHello(); B.sayHello(); //B b = new B(); // create an instance of B //b.sayHello(); // error can't override static method } }
3rd Sep 2017, 4:29 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
How clear you are !!! ~Thank You~
3rd Sep 2017, 4:43 AM
同學說他喜歡上課可是他沒來
同學說他喜歡上課可是他沒來 - avatar