私はオーバーライドしたい2つのメソッドを持つスーパークラスを持っています。これが私のコードです:
public class MyCustomClass extends SomeSuperClass {
protected MyCustomClass(params) {
super(params);
}
@Override
public void method1() {
super.method1();
/* here goes my code */
}
@Override
public void method2() {
super.method2();
/* here goes my another code */
}
SomeSuperClass オブジェクトをパラメーターとして渡すコンストラクターがあり、次に何をするか:
MyCustomClass object;
/* now i have object of type SomeSuperClass,
but with my own method1() and method2() */
object = (MyCustomClass) MyCustomClass.item(blahblah);
/* eclipse suggests casting, because MyCustomClass.item()
constructor still returns SomeSuperClass object */
otherobject = OtherConstructor.object(object);
//OtherConstructor passes SomeSuperClass object
それは正しいようですが、実行中に SomeSuperClass で java.lang.ClassCastException を取得しています。
SomeSuperClassObject を作成すると、オーバーライドされたメソッドが失われます。
キャストでは、Eclipse でエラーが発生していなくても、アプリケーションがクラッシュします。つまり、自分のメソッドで SomeSuperClass をオーバーライドして、OtherConstructor で使用する SomeSuperClass オブジェクトを取得するにはどうすればよいでしょうか? 重要な場合、このコードは Android アプリ用です。