package thinking.in.java;
public class PrivateOverride {
private void f(){
System.out.println("private f()");
}
private void ss()
{
System.out.println("this is a base class private method");
}
public void se()
{
System.out.println("this is a base class public method");
}
public final void sf()
{
System.out.println("this is a base class final method");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PrivateOverride po=new Derived();
po.f();
po.ss();
po.se();
po.sf();
((Derived) po).sp();
Derived dd= new Derived();
dd.f();
dd.sp();
dd.se();
dd.sf();
}
}
class Derived extends PrivateOverride{
public void f(){
System.out.println("public f()");
}
public void sp(){
System.out.println("Base Class don't have");
}
}
//输出结果为:
private f()
this is a base class private method
this is a base class public method
this is a base class final method
Base Class don't have
public f()
Base Class don't have
this is a base class public method
this is a base class final method
解析:由于private方法是final方法,而且对于子类是屏蔽的,因此,Derived类中的f()方法就
是一个全新的方法,既然基类中的方法在子类中不可见,因此也不能重载。由程序执行结果来看
,将基类引用指向子类对象后,基类引用可以访问基类独有的和不能被子类覆盖的方法(即
private,final,还有部分子类没有覆盖的),访问子类已经覆盖的方法时,执行的是子类中的
该方法。若要执行子类中特有的方法,就得将该引用强制转换为子类引用(如:((Drieved)
op).sp()),当定义子类引用指向子类对象后,则只能访问子类继承的(除屏蔽的private方法外
)和其有的方法。可见final方法只是不能被子类覆盖(我亲自试了,不能覆盖),但是可以被
子类继承
|
|