//Java 语言允许你去隐藏变量、嵌套类型,甚至是静态方法。
//当你在声明一个域、一个静态方法或一个嵌套类型时,如果其名字与基类
//中相对应的某个可访问的域、方法或类型相同,就会发生隐藏。
//一旦基类的一个方法或者域在子类中被隐藏,你就不能在子类的实例上调用它了(除了在子类内部,通过使用super 关键字)。
//如果一个类要隐藏一个域,而用来隐藏该域的域具有的可访问性比被隐藏域更具限制性,
//那么这就违反了包容性(subsumption)原则,即大家所熟知的Liskov 置换原则(Liskov Substitution Principle)
//这项原则指出,你能够对基类所作的任何事,都同样能够作用于其子类。
//不能使用实例方法覆盖基类的static方法。
//不能使用static方法隐藏基类的实例方法。
//不能使用static或者实例方法 隐藏和覆盖 基类的任何final类型方法。
//覆盖和隐藏的行为是指基类中那些在子类中可见的方法,如果基类中的方法使用了private修饰符,则可以随意在子类中使用相同签名的方法。
//final 修饰符对方法和域而言,意味着某些完全不同的事情。对于方法,final 意味着该方法不能被覆写
//(对实例方法而言)或者隐藏(对静态方法而言)。对于域,final 意味着该域不能被赋值超过一次。
//关键字相同,但是其行为却完全不相关。
//编译错误:Base.name被隐藏,所以访问的是Derived.name,而Derived.name是private的在类外部不可见。
//System.out.println(new Derived().name);
System.out.println(((Base) (new Derived())).name); //Base name
System.out.println(Derived.msg); //Derived msg
Base base = new Derived();
base.show(); //Derived.show(): Derived name
base.show1(); //Base.show1(): Base str
base.show2(); //Derived.show2(): Derived info
base.print(); //Base.print(): Base msg
Derived derived = new Derived();
derived.show1(); //Base.show1(): Base str
derived.show2(); //Derived.show2(): Derived info
derived.print(); //Derived.print(): Derived msg
class Base {
public String name = "Base name";
public String str = "Base str";
public static String msg = "Base msg";
public static String info = "Base info";
public void show() {
System.out.println("Base.show(): " + name);
}
public void show1() {
System.out.println("Base.show1(): " + str);
}
public void show2() {
System.out.println("Base.show2(): " + info);
}
public static void print() {
System.out.println("Base.print(): " + msg);
}
public final void print1() {
System.out.println("Base.print1(): ");
}
public final static void print2() {
System.out.println("Base.print2(): ");
}
}
class Derived extends Base {
private String name = "Derived name";
public String str = "Derived str";
public static String msg = "Derived msg";
public static String info = "Derived info";
/* 编译错误:静态方法无法隐藏基类的实例方法
public static void show() {
System.out.println("Derived.show()");
}*/
public void show() {
System.out.println("Derived.show(): " + name);
}
public void show2() {
System.out.println("Derived.show2(): " + info);
}
/* 编译错误:实例方法无法覆盖基类的静态方法
public void print() {
System.out.println("Derived.print()");
}*/
public static void print() {
System.out.println("Derived.print(): " + msg);
}
/* 编译错误:不能隐藏或者覆盖基类的final方法,不管是static还是实例方法。
public void print1() {
System.out.println("Derived.print1(): ");
}
public static void print1() {
System.out.println("Derived.print2(): ");
}
public static void print2() {
System.out.println("Derived.print2(): ");
}*/
}