TIJ学习系列--override final and private method

Override final 和 private 的 Class 会发生什么事?今天我试了一下。

 1 public class Class2 extends Class3{    
 2     public void printFT(){
 3         System.out.println("print final version from Class2");
 4     }
 5     //! cannot override @Override
 6     private void printPT(){
 7         System.out.println("print private version from Class2");
 8     }
 9     public static void main(String[] args){
10         Class2 class2 = new Class2();
11         Class3 class3 = class2;
12         class2.printFT();
13         class2.printPT();
14         //!class3.printFT(); //error 
15         //!class3.printPT(); //error 
16     }
17 }
18 
19 class Class3{
20     final void printFN(){
21         System.out.println("print final version from Class3");
22     }
23     private void printPT(){
24         System.out.println("print private version from Class3");
25     }    
26 }/* Output
27 print final version from Class2
28 print private version from Class2
29 *///:~

 

结论是:(首先private method 一定是final method)实际上,我们是不能override private method 和 final method的。因为private method是类外部不可见的,而final类是final的。我们所做的只是在新的Class中,定义了两个名字和父类中method相同的printFT() 和 printPT() method,那不是override。如果你尝试override父类的方法,在代码中加入@Override标签,编译器会complain “错误:方法不会覆盖或实现超类型的方法”。

用TIJ作者Bruce Eckel的话说是:

If a method is private, it isn’t part of the base-class interface. It is just some code that’s hidden away inside the class, and it just happens to have that name, but if you create a public, protected, or package-access method with the same name in the derived class, there’s no connection to the method that might happen to have that name in the base class. You haven’t overridden the method; you’ve just created a new method. Since a private method is unreachable and effectively invisible, it doesn’t factor into anything except for the code organization of the class for which it was defined.

 

posted on 2013-05-20 01:42  ZenLearner  阅读(377)  评论(0)    收藏  举报

导航