0

I have two classes A and B. B extends A. Now, in B, can I create an array list of objects of A.


public class A {

      // class fields
      // class methods  
}

import java.util.*;

public class B extends A {

List<Object> listname=new ArrayList<Object>();

A obj=new A();
listname.add(obj);
 }

Can I create an array list of objects at all ? By the way, above code gives error !

3
  • 2
    I think you mean B extends A... Commented Sep 24, 2012 at 2:24
  • Oh yes.. sorry for the typo !! Commented Sep 24, 2012 at 2:25
  • Do you mean how to get super class instance for a sub class? Commented Sep 24, 2012 at 2:31

3 Answers 3

4

Yes, I see no reason you cannot create an ArrayList of an object A.

But you can't do it the way you are doing it, you must do it in a method. You're trying to do it in the field declarations.

Try maybe adding it in the constructor?

So something like

public B() {
A obj=new A();
listname.add(obj);
}

Or maybe I just don't understand your question and I'm completely wrong.

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

Comments

2

The error is because you have code outside a method. Try this:

public class B extends A {

    private static List<Object> listname = new ArrayList<Object>();

    public static void main(String[] args) {
        A obj = new A();
        listname.add(obj);
    }
}

Comments

1

Use an instance initializer if you want to add items to your list outside of any method:

public class B extends A{
    private List<A> listOfA = new ArrayList<A>();

    {
         listOfA.add(new A());
    }

    public B(){
    }   
}

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.