读书人

java 暗藏实现(4)

发布时间: 2012-08-30 09:55:54 作者: rapoo

java 隐藏实现(4)
1.继承方法中私有权限的覆盖
package com.chinamworld.chapter53;
public class Father {
public void publicMethod(){
System.out.println("this is public method");
}
protected void protectedMethod(){
System.out.println("this is protected method");
}
void packageMethod(){
System.out.println("this is package method");
}
private void privatecMethod(){
System.out.println("this is private method" + " father");
}
public static void main(String [] args){
Sun sun = new Sun();
//不在同一个编译单元的同一个类中不能调用private方法
//sun.privatecMethod();
Father father = (Father)sun;
//上传后因为在父类的编译单元则可以调用私有方法---输出结果仍然是父类的输出
father.privatecMethod();
}
}

package com.chinamworld.chapter53;
public class Sun extends Father {
private void privatecMethod(){
System.out.println("this is private method" + " sun");
}
public static void main(String [] args){
Sun sun = new Sun();
//在同一个编译单元的同一个类中能调用private方法
sun.privatecMethod();
Father father = (Father)sun;
//上传后因为不和父类在同一个编译单元的同一个类中则可以调用私有方法
//father.privatecMethod();
}
}


由此可以看出:
1.私有方法本身是final的,根本不能被覆写,并且会对派生类隐藏;
2.只有非private方法才能被覆写;

读书人网 >编程

热点推荐