user3066571
user3066571

Reputation: 1471

Java - Compare child property on Parent Class Object

I have 2 classes, Foo, and BabyFoo which inherits Foo. In the Main method, I create an object Foo f1 = new BabyFoo(3);. BabyFoo has a compare method that overrides its parent method, that compares to make sure an object is of the same class, and making sure that the thing property is the same value as well.

My question, is in the compare method in the BabyFoo class, how do I access the thing property of the arguement getting passed in, as it is of type Foo, as the Foo class doesn't have a thing property, even though it was created as a 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
    }
}

Upvotes: 1

Views: 2612

Answers (4)

seal
seal

Reputation: 1143

You need to downcast Foo class to BabyFoo class.

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

Upvotes: 0

Nir Levy
Nir Levy

Reputation: 12953

Since the method gets Foo as a variable and not BabyFoo, you can't get to it's thing field without casting.

However, casting should be done safely, you need to verify you are comparing to a BabyFoo and not Foo

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

Upvotes: 0

Matthew Diana
Matthew Diana

Reputation: 1106

Check to see if the other object is of type BabyFoo. You can then perform a cast on the object, which would allow you to access the thing variable:

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

Upvotes: 0

billoot
billoot

Reputation: 47

You'll need to cast the other object to be a BabyFoo by writing something like

((BabyFoo)other).thing

This is assuming that everything else is how you want it.

Upvotes: 1

Related Questions