2016-10-13 3 views
1

Fooを継承する2つのクラスFooとBabyFooがあります。 Mainメソッドでは、オブジェクトFoo f1 = new BabyFoo(3);を作成します。 BabyFooには、その親メソッドをオーバーライドするcompareメソッドがあります。このメソッドは、オブジェクトが同じクラスであることを確認し、thingプロパティも同じ値であることを確認します。Java - 親クラスオブジェクトの子プロパティを比較

私の質問は、Fooクラスはthing性質を持っていないとして、私は、それがタイプFooであるようarguementのthingプロパティは、渡されたばかりアクセスしないか、BabyFooクラスでcompare方法でありますnew BabyFoo(3)として作成されています。

public abstract class Foo 
{ 
    public boolean compare(Foo other) 
    { 
     //compare checks to make sure object is of this same class 
     if (getClass() != other.getClass()) 
      return true; 
     else 
      return false; 
    } 
} 
public class BabyFoo extends Foo 
{ 
    protected int thing; 

    public void BabyFoo(int thing) 
    { 
     this.thing = thing; 
    } 
    @Override 
    public boolean compare(Foo other) 
    { 
     //compares by calling the parent method, and as an 
     //additional step, checks if the thing property is the same. 
     boolean parent = super.compare(other); 
     //--question do-stuff here 
     //how do I access other.thing(), as it comes in 
     //as a Foo object, which doesn't have a thing property 
    } 
} 

答えて

1

あなたは

((BabyFoo)other).thing

のようなものを書くことによってBabyFooするotherオブジェクトをキャストする必要がありますこれは、他のすべては、あなたがそれをする方法であると仮定しています。

0

otherオブジェクトのタイプがBabyFooかどうかを確認してください。あなたは、あなたがthing変数にアクセスすることを可能にすると思われる、オブジェクトのキャストを行うことができます

if (other instanceof BabyFoo) 
    BabyFoo bFoo = (BabyFoo) other; 
0

方法は変数ではなくBabyFooとしてFooを取得しているので、あなたはキャストせずに、それの事フィールドに取得することはできません。

しかし、キャスティングが安全に行われる必要があり、あなたはあなたがBabyFooクラスにFooクラスをダウンキャストする必要がBabyFooないFoo

@Override 
public boolean compare(Foo other) { 
    return other instanceof BabyFoo && 
     super.compare(other) && 
     this.thing == ((BabyFoo)other).thing; 
} 
0

と比較されていることを確認する必要があります。

@Override 
public boolean compare(Foo other) { 
    if (other instanceof BabyFoo) { // check whether you got the BabyFoo type class 
     BabyFoo another = (BabyFoo) other; 
     return super.compare(another) && another.thing == this.thing; 
    } 
    return false; 
} 
関連する問題