我有两个类,Foo和继承Foo的BabyFoo。在Main方法中,我创建一个对象Foo f1 = new BabyFoo(3);。 BabyFoo有一个覆盖其父方法的compare方法,该方法进行比较以确保对象属于同一类,并确保thing属性也具有相同的值。

我的问题是,在compare类的BabyFoo方法中,我如何访问传递的论据的thing属性,因为它是Foo类型,而Foo类却没有?即使具有thing属性,也不会具有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
    }
}

最佳答案

您需要通过编写如下内容将other对象转换为BabyFoo

((BabyFoo)other).thing

这是假设其他一切都是您想要的。

关于java - Java-比较父类对象的子属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40030667/

10-12 02:10