Java枚举编译错误:public类型EngineType需定义在独立文件中
Hey there! As someone who switched from C++ to Java, I totally get why this tripped you up—Java has some strict file structure rules that C++ doesn’t enforce. Let’s break down what’s happening and how to fix it.
Why You’re Seeing This Error
In Java, any public top-level type (class, enum, interface) must be defined in a separate file with exactly the same name as the type (including matching capitalization).
Looking at your code:
- You’ve got a top-level
enum Enginetypedefined in the same file as yourCarclass. - Even if you didn’t explicitly mark
Enginetypeaspublic, since yourCarclass references it with a public member (public Enginetype Enginetype;), Java treats it as needing to follow this file rule. - Also, note the capitalization mismatch in your error message (
EngineTypevs your enum’s nameEnginetype)—make sure you’re consistent with spelling and case everywhere!
Two Ways to Fix This
Option 1: Move the Enum to Its Own File
This is the standard Java practice for reusable types like enums:
- Create a new file named
Enginetype.java(match the enum’s name exactly, including the lowercase 't') in the samero.ase.classes1package. - Paste your enum into this file, and add the
publicmodifier so it’s accessible to theCarclass:package ro.ase.classes1; public enum Enginetype { gas, diesel, hybrid, electric } - Keep your
Car.javafile as is—since the enum is now in its own file, the compiler will stop throwing the error.
Option 2: Make the Enum an Inner Type in the Car Class
If you don’t need to use Enginetype outside the Car class, you can nest it inside the Car class:
package ro.ase.classes1; import ro.ase.interfaces1.mobility; public final class Car extends vehicle implements mobility,Cloneable { // Move the enum inside the Car class public enum Enginetype { gas, diesel, hybrid, electric } public final int maxNbofkm=1_000_000; public Enginetype Enginetype; private float speed; // Rest of your Car class code... public Car() { super(); Enginetype=Enginetype.gas; speed=0; } public Car(String _name,Enginetype _enginetype,float _speed) { super(_name,true); Enginetype=_enginetype; speed=_speed; } @Override public void DisplaySpeed() { System.out.println(String.format("The %s car runs with %f km/h", Enginetype.toString(),speed )); } @Override public void Start() { } @Override public void Stop() { System.out.println("The "+Enginetype.toString()+" car has stopped"); } }
This works because inner types don’t need their own separate files.
Quick Note on C++ vs Java
In C++, you can define multiple top-level types in a single source file without issues, but Java enforces this one-public-type-per-file rule to keep code organization consistent and make it easier for the compiler (and other developers!) to find and reference types.
内容的提问来源于stack exchange,提问作者Corina

