Java – Two classes in a single file

Two classes in a single file… here is a solution to the problem.

Two classes in a single file

I am preparing for the OCA Java 8 certification exam.

The book says:

If do you have a public class, it needs to match the filename. public
class animal2 would not compile in a file name Animal.java. The sample
code is:

public class Animal{
private String name;
}
class Animal2{

}

However, if I create a Java file called “Animal.java” and I put the code into it and compile it, the compiler generates two java classes, “animal.class” and “animal2.class.

Is the study guide wrong?

Solution

Basically, the

book says that if a file name is Animal, the public class must also be called Animal, otherwise an error will occur.

class Animal2 is not public, which is why it compiles normally.

What you can do is have a public class in the public class:

public class Animal{

public class Animal2{
        ...
    }

...

}

It’s impossible:

public class Animal{
      ....
}

public class Animal2{
      ....
}

Related Problems and Solutions