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.
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.
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...);
}}
}
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(.........);
}
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.
List type should be:
ArrayList <? extends Employee> list = new ArrayList<>();