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.
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.
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.
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).
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.
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 {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With