0

I have a Parent class. I made an array of 3 parent objects. I also have a child class. Is it possible that I can have 1 of those 3 array elements be a child object?

private ParentClass[] a = new ParentClass[3]

ParentClass a[] = {
     new ParentClass("0"),
     new ParentClass("1"),
     new ChildClass("2")
};

This works fine. But I'm wondering, is this the correct way of doing it or is there any easier/cleaner way?

New to java btw from C.

8
  • 4
    what happened when you tried it? Commented Sep 17, 2019 at 16:24
  • After running the above code, please don't post I ran that particular code and it worked question. Commented Sep 17, 2019 at 16:28
  • @roundAbout What do you mean? Commented Sep 17, 2019 at 16:29
  • @Reimeus Didn't get any errors. Just wondering, is this the right/best way of doing it? Java has so many new data types that I'm getting used to (coming from a C background). Commented Sep 17, 2019 at 16:42
  • Yes, it's the correct way. You'd use a Collection (like List) instead of arrays 99% of the time though. Commented Sep 17, 2019 at 16:45

1 Answer 1

2

Alternatively you can do the following, List.of comes with Java 9. The returned list is immutable, immutable objects are very nice in a lot cases. Also in Java, we do Interface instance = new ImplementationClass(), for example List<Class> = new ArrayList<>(), ArrayList implements List interface

List<ParentClass> list = List.of( new ParentClass("0"), new ParentClass("1"), new ChildClass("2") );

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

1 Comment

Prior Java has Arrays.asList(...) .

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.