繁体   English   中英

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

[英]Java - Compare child property on Parent Class Object

我有 2 个类,Foo 和继承 Foo 的 BabyFoo。 在 Main 方法中,我创建了一个对象Foo f1 = new BabyFoo(3); . BabyFoo 有一个比较方法,它覆盖了它的父方法,比较以确保一个对象是同一个类,并确保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
    }
}

您需要通过编写类似的内容将other对象转换为 BabyFoo

((BabyFoo)other).thing

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

检查other对象是否属于BabyFoo类型。 然后,您可以对对象执行强制转换,这将允许您访问thing变量:

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

由于该方法将Foo作为变量而不是BabyFoo ,因此您无法在不进行转换的情况下访问它的事物字段。

但是,转换应该安全地完成,您需要验证您正在比较的是BabyFoo而不是Foo

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

您需要将FooBabyFooBabyFoo类。

@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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM