I could not find a question like mine, so I hope this is not a duplicate.
Again on how to redefine and hide. I think - but I could be wrong - I understood both.
The following code behaves as expected, both methods were hidden. method1, because it is a private method and private methods cannot be overridden only by the hidden methods of method2, because static and static methods cannot be overridden, they can only be hidden.
public class Child extends Parent { public void method1(){System.out.println("child");} public static void method2(){ System.out.println("static child");} } class Parent{ private void method1(){ System.out.println("parent");} public static void method2(){ System.out.println("static parent");} public static void main(String[] args){ Parent p = new Child(); p.method1();
If I read the specs, it says:
http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.3.3
A method can be declared final to prevent subclasses from being overridden or to hide it.
If I change method1 in the parent class to "final"
private final void method1(){ System.out.println("parent");}
Everything works perfectly. edit start: I was expecting a compiler error to indicate that the final methods cannot be hidden, but this did not happen. : edit end
Question # 1: does this mean that only hidden methods can be hidden? In the book I am reading (OCA study guide, Jeanne Boyarski and Scott Selikoff p. 252), they clearly say that the hidden method is hidden.
Then I changed method2 in the parent class to
public final static void method2(){ System.out.println("static parent");}
Now the compiler complains, the error says: βThe child cannot override method2 ()β, which is quite confusing because I thought I was trying to hide the method.
Question No. 2: Should it be "The child cannot hide method2 ()"?
edit start: I am well aware that there is no redefinition here, but as the mentioned specifications mention, the final version of the modifier prohibits overriding or hiding methods, so I put it in the header. : edit end