私はベースクラス "Shapes"と拡張クラス "Circle"を持っています。どちらもgetNameメソッドを持っています。 私のテストクラスは「ドライバ」クラスです。Javaアップキャストスコープ解決の問題
サークルオブジェクトをシェイプにアップキャストし、それをpolyTestという関数に渡します。 その関数ではgetNameを呼び出す必要がありますが、getオブジェクトのcircleオブジェクトの実装をトリガーするのではなく、基本クラスの実装をトリガーする必要があります。
super.getName()は機能しません。
私のコードは以下のとおりです。
public class Driver{
public static String polyTest (Shapes s){
return s.getName();
/*Instead of s.getName()... (gives me the Circle class implementation of getName())
I want to call s.Shapes::GetName, the base class implementation of getName. */
}
public static void main(String[] args){
Circle c = new Circle();
//Test Basic inheritance & basic polymorphism.
//System.out.print(c.getName());
//Upcast test.
Shapes s = (Shapes) c;
System.out.print(polyTest(s));
}
}
public class Circle extends Shapes{
Circle(){
super();
}
public String getName(){
return "I am a Circle";
}
}
public abstract class Shapes{
Shapes(){
}
public String getName(){
return "I am a Shape";
}
}
デザインに何か問題があるように見えます。ところで、Shapesにアップキャストする必要はありません。何をしたいですか? – khachik