Naveen Attri Naveen Attri - 3 months ago 14
Java Question

Check if a member variable exists in an Object from superClass?

My classes are defined in a way like this

class SuperClass
{
protected boolean hasProperty;
}

class SubOne extends SuperClass
{

protected Property prop;

SubOne()
{
this.hasProperty=true;
this.prop=new Property();
}
}

class SubTwo extends SuperClass
{
SubTwo()
{
this.hasProperty=false;
}
}


I needed the different objects of SubOne and SubTwo in a single Array, because I want objects of both classes interact with each and every one else and also I actually have four SubClasses(I've taken only two here for example), so I wanted to put them all in single Array. I used the following thing.

SuperClass[] superClass={
new SubOne(),
new SubTwo()
}


Now, while iterating the loop, if I write the following, it gives me error. I've spent time in searching for soution, but I couldn't find it.

for(Superclass superObj:superClass)
{
if(superObj.hasProperty)
System.out.print(superObj.prop.something);
//when hasProperty is false, this statement should not be called,
//but compiler gives error
else
System.out.print("Something");
}

Answer

One solution would be to have a method in the superclass called getProperty which can be called from any instance once the presence of the property is verified. In the superclass, the method can return null or throw an exception; override it in the subclass to return the actual property. Like so:

class SuperClass
{
    protected boolean hasProperty;

    protected Property getProperty()
    {
        throw new UnsupportedOperationException();
    }
}

class SubOne extends SuperClass
{
    protected Property prop;   

    SubOne()
    {
        this.hasProperty=true;
        this.prop=new Property(); 
    }

    @Override
    protected Property getProperty()
    {
        return prop;
    }
}

class SubTwo extends SuperClass
{
    SubTwo()
    {
        this.hasProperty=false;
    }
}

And the code for the iteration would be as follows:

if (superObj.hasProperty)
    System.out.println(superObj.getProperty().something);
else
    System.out.println("Something");

The advantage of this over a template method is that it works for any application of the properties without needing to be changed.

Comments