package com;
class Super {
public void opration(Super s) {
System.out.println("Super operation!");
}
};
class SuperA extends Super {
public void opration(SuperA a) {
System.out.println("SuperA operation A!");
}
public void opration(SuperB b) {
System.out.println("SuperA operation B!");
}
public void opration(Super s) {
if (s instanceof SuperB)
System.out.println("S is a instance of Class SuperB!");
if (s instanceof SuperA)
System.out.println("S is a instance of Class SuperA!");
if (s instanceof Super)
System.out.println("S is a instance of Class Super!");
System.out.println("SuperA operation S!");
System.out.println();
}
};
class SuperB extends Super {
public void opration(SuperA a) {
System.out.println("SuperB operation A!");
}
public void opration(SuperB b) {
System.out.println("SuperB operation B!");
}
public void opration(Super s) {
if (s instanceof SuperB)
System.out.println("S is a instance of Class SuperB!");
if (s instanceof SuperA)
System.out.println("S is a instance of Class SuperA!");
if (s instanceof Super)
System.out.println("S is a instance of Class Super!");
System.out.println("SuperB operation S!");
System.out.println();
}
};
public class Test {
private static Super a;
private static SuperB b;
public static void main(String[] args) {
b = new SuperB();
a = new SuperA();
System.out.println("Class name of variable a is " + a.getClass().getName());
System.out.println("Class name of variable b is " + b.getClass().getName());
System.out.println();
a.opration(b);
a.opration(a);
b.opration(a);
b.opration(b);
}
}
结果为:
Class name of variable a is com.SuperA
Class name of variable b is com.SuperB
S is a instance of Class SuperB!
S is a instance of Class Super!
SuperA operation S!
S is a instance of Class SuperA!
S is a instance of Class Super!
SuperA operation S!
S is a instance of Class SuperA!
S is a instance of Class Super!
SuperB operation S!
SuperB operation B!
a是Super类型的引用,指向SuperA类型的对象!
所以a只能调用类Super中存在的方法,
如果方法被子类SuperA覆盖了,则调用子类SuperA中覆盖了的方法,
对于子类中的新方法,a无权调用。
b是SuperB类型的引用,指向SuperB类型的对象!
所以b可以调用类SuperB中所有的方法。