2

at the moment, I am wondering if there is a way to add a child class object to a parent class array.

I have code that follows the generic line of:

    public abstract class Parent {  
        ...
    }

    public class Child extends Parent {
        ...
    }

And I have an array that follows along the lines of:

Parent[] array = new Parent[number];

I want to be able to add my child objects to this array like:

array[0] = new Child();

However whenever I do this, I get an error message saying that they are incompatible types. I know this can be achieved in ArrayList but I want to see if it is possible in the format above. Is there a way to achieve this without ArrayList?

4
  • 2
    This doesn't compile Parent[] array = new Parent[]; I suspect your code is different which is the reason it doesn't compile. Commented Dec 18, 2013 at 11:18
  • Ahh okay, I come from a C# background and quite new to Java. Any help will be appreciated. Commented Dec 18, 2013 at 11:19
  • I edited the number in the array if that is what you are talking about. Commented Dec 18, 2013 at 11:20
  • 1
    @Brian It must work then. Commented Dec 18, 2013 at 11:21

3 Answers 3

4

The following code compiles without error:

public abstract class Parent {

  private static class Child extends Parent {}

  public static void main(String[] args) throws Exception {
    Parent[] array = new Parent[1];
    array[0] = new Child();
  }
}

This is very similar to the code in your question. So perhaps compare your code with mine and spot the difference?

In Java (and in most/all OO languages), this polymorphic behaviour is standard and completely correct.

Sign up to request clarification or add additional context in comments.

1 Comment

I feel so foolish, I added a completely different class which is named similarly to the child class. Thank you guys for your help.
0

How about trying this:

    enter codepublic abstract class Parent {

  private static class Child extends Parent {}

  public static void main(String[] args) throws Exception {
    Parent[] array = new Parent[1];
    Parent child = new Child();
    array[0] = child;
  }
} here

Comments

0

Just put size of array when creating, everything works with it :)

Parent[] array = new Parent[5]; array[0] = new Child();

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.