String name = "A";
String getName(){
return name;
}
String greeting(){
return "class A";
}
}
class B extends A{
String name = "B";
String greeting(){
return "class B";
}
}
public class Test {
public static void main(String[] args){
A a = new A();
A b = new B();
System.out.println(a.greeting()+" has name "+a.getName());
System.out.println(b.greeting()+" has name "+b.getName());
}
}
A a = new A(); a為A()的建構子宣告為A物件
A b = new B(); b為B()的建構子宣告為A物件
所以會印出
Class A has name A
Class B has name A
裡面最有問題的是 b.getName() 會印出 A吧!是因為 b是 B()的建構子,可是物件是A的所以才會印出A。
沒有留言:
張貼留言