Julian Young
Julian Young

Reputation: 912

Java LinkedList Object inheritance overriden

I'm fairly new to Java, I have a linkedList of class ObjectType, I have various subclasses of ObjectType being added to the linkedList, when I pull the object out I am forced to pass it a type of ObjectType and seem to lose the inherited properties of the subclass.... Can anyone shed some light on this for me?

//LIST STORING OBJECT
public class MyObjectList{

    private LinkedList<ObjectType> queue = new LinkedList<ObjectType>();

    public MyObjectList()
    {
        queue = new LinkedList<ObjectType>();
    }

    public ObjectType addObject(ObjectType myObject)
    {
        queue.add(myObject);
        return myObject;
    }

}

//MY BASIC OBJECT
public abstract class ObjectType {

    public int objectWidth;

    public ObjectType () {}
}

//MY EXTENDED OBJECT BOX
public abstract class Box extends ObjectType {

    public int objectWidth = 50;

    public ObjectType () {}
}

//MY EXTENDED OBJECT PLATE
public abstract class Box extends ObjectType {

    public int objectWidth = 25;

    public Box() {}
}

// OK so now if I add a load of boxes to my list of boxes will have their objectWidth set to zero!

mList = new MyObjectList;

for (int i=0;i<10;i++)
{
   mObject = mList.addObject( new Box );
}

It's important to remember that my list is supposed to be made up of different object types eventually so the baseObject needs to remain as it is. if possible!

Upvotes: 0

Views: 826

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533550

A better pattern to use is a constant per class like.

//MY BASIC OBJECT
public abstract class ObjectType {

    public abstract int objectWidth();

    public ObjectType () {}

}

//MY EXTENDED OBJECT BOX
public class Box extends ObjectType {

    public int objectWidth() { return 50; }

    public ObjectType () {}
}

Upvotes: 0

You cannot override fields in Java, so if you want to set objectWidth to 50 in your subclass, you would do it like this:

public abstract class ObjectType {
    public int objectWidth;
    public ObjectType () {}
}

public abstract class Box extends ObjectType {
    public Box () {
        objectWidth = 50;
    }
}

Upvotes: 2

Keppil
Keppil

Reputation: 46219

Since variables aren't overridden, but hidden, the approach of declaring the variable again in each subclass and giving it a new value doesn't work.

One way to solve this is to give your abstract class a method, e.g. getObjectWidth(), and override that in each subclass. Since methods can be overridden, this way the specific value will be shown for each object.

Upvotes: 1

Related Questions