(七)『Javaプログラミング思想』——多態の欠陥
6485 ワード
1.プライベートメソッドを上書きできません
【運転結果】:private f()public f()
2.ドメインがマルチステートでない(通常の方法のみがマルチステートである)
【運転結果】:
sup.field = 0 sup.getField() = 1sub.field = 1 sub.getField() = 1 sub.getSuperField = 0
3静的方法は多態性を呈しない
【運転結果】:
Base staticGet()Derived dynamicGet()
package chapter8;
/**
* " "
*/
public class PrivateOverride {
private void f() {
System.out.println("private f()");
}
public static void main(String[] args) {
PrivateOverride po=new Derived();
po.f();
Derived d=new Derived();
d.f();
}
}
class Derived extends PrivateOverride {
public void f() {
System.out.println("public f()");
}
}
【運転結果】:private f()public f()
2.ドメインがマルチステートでない(通常の方法のみがマルチステートである)
/**
*
*/
package chapter8;
/**
* :
*/
class Super {
public int field = 0;
public int getField() {
return field;
}
}
class Sub extends Super {
public int field = 1;
public int getField() {
return field;
}
public int getSuperField() {
return super.field;
}
}
public class FieldAccess {
public static void main(String[] args) {
Super sup = new Sub();
System.out.println("sup.field = " + sup.field + " sup.getField() = "
+ sup.getField());
Sub sub = new Sub();
System.out.println("sub.field = " + sub.field + " sub.getField() = "
+ sub.getField() + " sub.getSuperField = "
+ sub.getSuperField());
}
}
【運転結果】:
sup.field = 0 sup.getField() = 1sub.field = 1 sub.getField() = 1 sub.getSuperField = 0
3静的方法は多態性を呈しない
package chapter8;
/**
*
*/
class StaticSuper {
public static String StaticGet() {
return "Base staticGet()";
}
public String dynamicGet() {
return "Base dynamicGet()";
}
}
class StaticSub extends StaticSuper {
public static String StaticGet() {
return "Derived staticGet()";
}
public String dynamicGet() {
return "Derived dynamicGet()";
}
}
public class StaticPolymorphism {
public static void main(String[] args) {
StaticSuper sup = new StaticSub();
System.out.println(sup.StaticGet());
System.out.println(sup.dynamicGet());
}
}
【運転結果】:
Base staticGet()Derived dynamicGet()