SCJP 1.6版考題 064
出自 陳富國維基館
class A { 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 Client { 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()); } }
解答
解說:
方法多形是說方法的決定是以物件為判斷的依據 b.getName()是叫用A型態的getName(因為B類別沒有getName),所以A型態的getName就是取得A的name,若在B加上getName結果就不一樣了! class A { String name = "A"; String getName() { return name; } String greeting(){ return "class A"; } } class B extends A { String name = "B"; String getName() { return name; } String greeting() { return "class B"; } } public class Client { 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()); } }
|