-4

I'm trying to create an array list of different classes which use the same abstract class.

However, I get this error.

<identifier> expected, illegal start of type, package list does not exist.

All in the image.

Tiago Almeida
  • 137
  • 1
  • 1
  • 9
user2102697
  • 29
  • 1
  • 8
  • 1
    Give the error message here. – Ajay S Apr 01 '13 at 16:45
  • Sorry for that, the error is expected, illegal start of type, package list does not exist. – user2102697 Apr 01 '13 at 16:46
  • don't post images on 3rd party sites, post the errors in your question as inline text or this will get down voted and deleted quickly –  Apr 01 '13 at 16:54
  • Copy and paste the broken code here (with just enough context for us to understand, dont go pasting everything), and then type out the error you're getting. This will make it much easier for us to answer quickly, as typing out the classes and whatnot from your image costs us valuable time. – Quetzalcoatl Apr 01 '13 at 16:57

4 Answers4

2

Your list.add is not taking place in a constructor or method, but merely floating in your class, which is not allowed. Try putting it in a constructor if you need it to take place upon class instantiation or create a method to add parameters passed to it into your list.

Alternatively for in-line instantiation: (but be sure to look at the pros and cons of double brace initialisation)

E.g.

public class TestEmployee {

    private ArrayList<Employee> list = new ArrayList<Employee>() {{
        add(new SalariedEmployee...);
        add(new SalariedEmployee...);
    }}

}
Community
  • 1
  • 1
Quetzalcoatl
  • 3,037
  • 2
  • 18
  • 27
1

Actually I saw your picture and found that you are trying to add the element in ArrayList outside the method or block.

Instead of this write this in method.

public void method() {
   list.add(.........);
}
Ajay S
  • 48,003
  • 27
  • 91
  • 111
0

You don't have those statements wrapped inside any method. The instantiation of list field is fine, but assigning some values to it? No. Put it inside a block or method.

asgs
  • 3,928
  • 6
  • 39
  • 54
0

List type should be:

ArrayList <? extends Employee> list = new ArrayList<>();
Tiago Almeida
  • 137
  • 1
  • 1
  • 9