Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java public interface and public class in same file

Tags:

java

In a single .Java file, is it possible to have a public interface and a public class (which implements the interface)

I'm new to Java coding and it is written on most places on the net that a .java file cannot contain more than 2 public class. I want to know if it is true for the interface and a class also.

like image 246
Linda Peters Avatar asked Aug 20 '11 17:08

Linda Peters


People also ask

Should interfaces be in a separate file?

You should put it in a separate file. That way it's easier to swap in a different implementation, or make the interfaces (the API of your system) available for others to code against without knowing the details of your implementation, or having to drag in related dependencies.

Can you have multiple public classes in a Java file?

The name of the Java file should be the same as the name of the public class in that file. Multiple classes in a Java program can either be nested or non-nested.

Why we can not declare multiple public classes in single .Java file?

So the reason behind keeping one public class per source file is to actually make the compilation process faster because it enables a more efficient lookup of source and compiled files during linking (import statements).

Can a public class implement an interface?

Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. By convention, the implements clause follows the extends clause, if there is one.


1 Answers

No, it's not possible. There may be at most one top-level public type per .java file. JLS 7.6. Top Level Type Declarations states the following:

[…] there must be at most one [top level public] type per compilation unit.

You could however have a package-protected class in the same file. This compiles fine (if you put it in a file named Test.java:

public interface Test {
    // ...
}

class TestClass implements Test {
    // ...
}
like image 63
aioobe Avatar answered Sep 20 '22 22:09

aioobe