0

I am trying to figure out how to define an array of a certain type of objects that will include the subclasses as well. This is what I have :

Property[] list = new Property[100];

I believe this will define an array of 100 properties, but is it possible for this array to include SubProperty as well. SupProperty is an extension of the Property class.

Thanks very much.

4
  • what kind of subproperty Commented May 31, 2013 at 7:01
  • 1
    It can include SubProperty as well, but while retreiving, you'll have to cast it as SubProperty sub = (SubProperty) list[10]. Assuming, list[10] is an instance of SubProperty and not Property Commented May 31, 2013 at 7:01
  • what problem you are facing..? Commented May 31, 2013 at 7:02
  • Read - docs.oracle.com/javase/tutorial/java/concepts/inheritance.html Commented May 31, 2013 at 7:08

4 Answers 4

2

Yes it is possible for the array to include the SubProperty as well. Please find the code below -

class SubProperty extends Properties{
}

and

Properties[] obj = new Properties[100];
obj[1] = new SubProperty();

you can get back your Object, like -

for(Properties prop: obj){
    if(prop instanceof SubProperty){
        SubProperty subProp = (SubProperty)prop;
        System.out.println(subProp);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you have

Animal[] list = new Animal[100]

Would you be able to add a Dog to that array?, If a Dog is an animal, you will be able to do Animal dog = new Dog(); That's what inheritance is, if you want to know more about it go here

Comments

0

Yes, it is. A SubProperty object is a Property object. You can always swap a subclass for its parent.

Comments

0

You can use a subclass wherever its superclass can be used. This is OOP substitution principle. It also applies in this situation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.