有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

父类对象上的继承Java比较子属性

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

我的问题是,在BabyFoo类中的compare方法中,我如何访问传入的参数的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
    }
}

共 (0) 个答案