OneMoreError
OneMoreError

Reputation: 7728

Creating an array list of objects

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 !

Upvotes: 0

Views: 209

Answers (3)

wulfgarpro
wulfgarpro

Reputation: 6924

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(){
    }   
}

Upvotes: 1

Bohemian
Bohemian

Reputation: 424993

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);
    }
}

Upvotes: 2

Austin
Austin

Reputation: 4929

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.

Upvotes: 4

Related Questions