Class or interface expected java что делать

от admin

Ошибка компилятора Java: «ожидается класс, интерфейс или перечисление»

В этом кратком руководстве мы поговорим об ошибке компилятора Java «ожидается класс, интерфейс или перечисление» . В основном с этой ошибкой сталкиваются разработчики, которые являются новичками в мире Java.

Давайте рассмотрим несколько примеров этой ошибки и обсудим, как их исправить.

2. Неуместные фигурные скобки

Основной причиной ошибки «ожидается класс, интерфейс или перечисление» , как правило, является неуместная фигурная скобка _ «>» _ . Это может быть дополнительная фигурная скобка после урока. Это также может быть метод, случайно написанный вне класса.

Давайте посмотрим на пример:

В приведенном выше примере кода в последней строке есть дополнительная фигурная скобка __ «>», что приводит к ошибке компиляции. Если мы удалим его, код скомпилируется.

Давайте посмотрим на другой сценарий, где эта ошибка происходит:

В приведенном выше примере мы получим ошибку, потому что метод printHello () находится вне класса MyClass . Мы можем исправить это, переместив закрывающие фигурные скобки «>» в конец файла. Другими словами, переместите метод printHello () внутрь MyClass .

3. Заключение

В этом кратком руководстве мы обсудили ошибку компилятора Java «ожидаемый класс, интерфейс или перечисление» и продемонстрировали две вероятные основные причины.

How to Fix Error: “Class, Interface, or Enum Expected” ?

The braces in java are served as a scope limit . The beginning and end of a code block are indicated by curly brackets.

Curly brackets cause the compile-time error known as the class interface or enum expected error in Java. This issue typically happens when the program ends with an extra curly brace.

Since everything in Java is programmed inside a class, interface, or enum, if you close the curly bracket for one class and add another, the compiler will assume that another class is starting and will complain about the class, interface, or enum keyword, as illustrated in the following program:

Code explanation If we compile this code it will raise this error

because of extra braces.

Misplaced Curly Braces

The root cause of the “class, interface, or enum expected” error is typically a misplaced curly brace “>”. This can be an extra curly brace after the class. It could also be a method accidentally written outside the class.

Code Explanation The following error will be raised

To solve this error simply remove extra brace

Function Outside Class (Intro+ Add Code Example Ti Fix Error)

A method present outside of a class may also be the cause of this problem. The compilation process will fail since this method does not belong to any class. Moving the method within the class will fix this issue.

Code Explanation In Above code method1 is outside of class classb this will raise error.To solve this placed method1 inside of classb.

Multiple Package

In a Java file, only one package can be declared. The expected compilation error for a class, interface, or enum will occur if we have more packages than necessary.

How to fix «class, interface, or enum expected» error in Java? Example

Today, I am going to tell you about one such error, «class, interface, or enum expected». This is another compile-time error in Java that arises due to curly braces. Typically this error occurs when there is an additional curly brace at the end of the program.

Since everything is coded inside a class , interface, or enum in Java, once you close the curly brace for an existing class and add another closing curly braces, the compiler will expect another class is starting hence it will complain about class, interface, or enum keyword as shown in the following program:

If you compile this program using javac, you will get the following error:

Since this is a small program, you can easily spot the additional curly brace at the end of the problem but it’s very difficult in a big program with several classes and methods.

This becomes even tougher if you are not using any IDE like Eclipse or NetBeans which will give you a visible sign of where an error is. If you know how to use Eclipse or any other Java IDE, just copy-paste your code into IDE and it will tell you the exact location of the error which hint to solve.

Читать:
X 2 y 2 z 2 0 что за поверхность

Alternatively, if you are coding in Notepad, I assume you are a beginner, then try to correctly indent your code. n our example program above, notice that the two curly braces at the end of the program are at the same indentation level, which cannot happen in a valid program. Therefore, simply delete one of the curly braces for the code to compile, the error will go away as shown below:
So, next time you get the «class, interface, or enum expected» error, just check if you additional curly braces a the end of your program.

How to fix class interface or enum expected error in java

In this post, we will see how to fix "class interface or enum expected" error in java.

There can be multiple reason for getting this error.

Due to method outside class body

This error you will generally get when you have accidentally put your method outside class body.
Let’s see with the help of simple example.

You will get below error when you run javac command.

But if you use eclipse ide, you will get below error.

As you can see, eclipse provides you much better information regarding this error.
I have given a very simple example, you might get this error in complex code. It is hard to identify issues with that so I will recommend you to use some ide like eclipse.

Forgot to declare class at all

This might sound silly but if you forgot to declare class at all, you will get this error.Please check if you have declated class, interface or enum in your java file or not.

That’s all about class interface or enum expected error in java.I hope it will resolve this error for you.

Was this post helpful?

Share this

How to fix illegal start of expression error in java

Error could not create the Java virtual machine in java

Related Posts

Author

Related Posts

[Fixed] Unsupported class file major version 61 in Java

Table of ContentsReason for Unsupported class file major version 61 in JavaSolution for Unsupported class file major version 61 in JavaAndorid studio/Intellij Idea with gradleAny other scenario In this post, we will see how to fix Unsupported class file major version 61 in Java. Reason for Unsupported class file major version 61 in Java You […]

java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

HashMap values cannot be cast to list

[Fixed] java.util.HashMap$Values cannot be cast to class java.util.List

Table of ContentsWhy HashMap values cannot be cast to list?Fix for java.util.HashMap$Values cannot be cast to class java.util.List In this post, we will see how to fix error java.util.HashMap$Values cannot be cast to class java.util.List. Why HashMap values cannot be cast to list? HashMap values returns java.util.Collection and you can not cast Collection to List […]

Unable to obtain LocalDateTime from TemporalAccessor

[Fixed] Unable to obtain LocalDateTime from TemporalAccessor

Table of ContentsUnable to obtain LocalDateTime from TemporalAccessor : ReasonUnable to obtain LocalDateTime from TemporalAccessor : FixLocalDate’s parse() method with atStartOfDay()Use LocalDate instead of LocalDateTime In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8. Unable to obtain LocalDateTime from TemporalAccessor : Reason You will generally get […]

[Solved] Variable might not have been initialized in Java

Learn about how to solve Variable might not have been initialized in Java.

[Solved] Class names are only accepted if annotation processing is explicitly requested

Learn about how to fix class names are only accepted if annotation processing is explicitly requested in java.

Похожие статьи