Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Beginner Java) class, interface, or enum expected

Tags:

java

Forgive me for posting a question very similar to one that I posted last night. I've simplified the problem in order to ask something more specific:

I'm getting a (class, interface, or enum expected) error when I use the following code:

import java.util.*;


ArrayList<egg> eggys = new ArrayList<egg>;


public class EggTest{
    public static void main(String [] args){

        egg a = new egg();
        egg b = new egg();

        eggys.add(a);
        eggys.add(b);

        for (egg eggo :eggys){
            System.out.println(eggo.size);
        }
    }
}

The output from the compiler is:

eggys.java:4: class, interface, or enum expected
ArrayList<egg> eggys = new ArrayList<egg>;
^
1 error

I'm not doing something right. Can anyone help me figure out how to use ArrayList?

like image 583
Java Noob Avatar asked Jul 26 '13 17:07

Java Noob


2 Answers

You can only declare variables inside a class or method; not as top-level code.

like image 195
SLaks Avatar answered Oct 01 '22 01:10

SLaks


Java is a purely object oriented langauage, which means any/all the properties should belong to an entity i.e class/interface/enums. In your case you have defined a property/variable as mentioned below, which does not belong to either a class/enum/interface and hence java compiler complains for it.

ArrayList<egg> eggys = new ArrayList<egg>;

You cannot have this property like global variables in other programming languages. Java's purely object oriented nature does not allow so.

Also as mentioned by "skiwi" in comment below, you have syntax error in your ArrayList definition as well. You are missing the parentheses towards the end. It should be corrected to:

ArrayList<egg> eggys = new ArrayList<egg>();
like image 36
Juned Ahsan Avatar answered Oct 01 '22 02:10

Juned Ahsan