user1568613
user1568613

Reputation: 123

More than one java class in the same file

I am having trouble with some java code:

I created a class named clsEnum, and I want it to contain not just one class.

enum EnumDocument
{
    DNI(1), RUC(5), Grupo(7),Sucursal(8);

    private int value;

    EnumDocument(int value){
        this.value = value;
    }

    public int getValue(){
        return this.value;
    }
}

enum EnumTypeRoleCredential
{
    Employee(81), Client(82), Supplier(83);
    private int value;

    EnumTypeRoleCredential(int value){
        this.value = value;
    }

    public int getValue(){
        return this.value;
    }
}

Yes I know, I forgot to put the main class(clsEnum), but in this case I dont want to put it. This is the way I want it to work. So, when a I create an enumDocument object or a EnumTypeRoleCredential object, in a class wich is in the same package, I dont have any problem, but when I create an object in another class wich is in another package, the IDE(Eclipse juno) suggest to use "public", but when y use it, i get an error that says that the class needs its own file.

I use to do this en Visual Studio c#.net. Can it be done in Java, or i have to put necessary the subclasses into the main class.

Thanks.

Upvotes: 0

Views: 114

Answers (3)

Pranshu jain
Pranshu jain

Reputation: 1

In single java file you can have multiple no of classes but there could be only one public class and name of public class should as same as name of name of your file. That public class can be use anywhere

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340983

In Java you can have at most one public class (file name must match this class name) and arbitrary number of non-public classes. public class can be used everywhere once imported. non-public classes can be used only in the same package.

These are the rules, there's nothing you can do about it.

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213391

  • In a single Java file, you can have at most one public class, and if it is present, then the name of your java file should be the same as your public class name..

So, you can make only one of your enums public, and your file name should be the name of that public enum with .java extension..

  • And your public static void main will also go into that public class

  • And also, **this is important - If in a file you have enums, classes and interfaces all of them, then also only one of them would be public.

Upvotes: 3

Related Questions