In Java, the class interface or enum expected error is a compile-time error. There can be one of the following reasons we get “class, interface, or enum expected” error in Java:
Case 1: Extra curly Bracket
Java
class Hello {
public static void main(String[] args)
{
System.out.println("Helloworld");
}
}
}
In this case, the error can be removed by simply removing the extra bracket.
Java
class Hello {
public static void main(String[] args)
{
System.out.println("Helloworld");
}
}
Case 2: Function outside the class
Java
class Hello {
public static void main(String args[])
{
System.out.println("HI");
}
}
public static void func() { System.out.println("Hello"); }
In the earlier example, we get an error because the method func() is outside the Hello class. It can be removed by moving the closing curly braces “}” to the end of the file. In other words, move the func() method inside of Hello.
Java
class Hello {
public static void main(String args[])
{
System.out.println("HI");
}
public static void func()
{
System.out.println("Hello");
}
}
Case 3: Forgot to declare class at all
There might be a chance that we forgot to declare class at all. We will get this error. Check if you have declared class, interface, or enum in your java file or not.
Case 4: Declaring more than one package in the same file
Java
package A;
class A {
void fun1() { System.out.println("Hello"); }
}
package B;
public class B {
public static void main(String[] args)
{
System.out.println("HI");
}
}
We can not put different packages into the same source file. In the source file, the package statement should be the first line.
Java
package A;
class A {
void fun1() { System.out.println("Hello"); }
}
public class B {
public static void main(String[] args)
{
System.out.println("HI");
}
}
Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:
Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks
Last Updated :
28 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...