开发者

Java public interface and public class in same file

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.


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 {
    // ...
}


You can have as many public classes as you want in one file if you use nested classes. In your example:

public interface I {
    public class C implements I {
        ...
    }

    public class D implements I {
        ...
    }

    ...
}


public interface A
{
    public void helloWorld();

    public static class B implements A{

        @Override
        public void helloWorld() {
            System.out.print("Hello World");

        }

    }
}


The Java rule is that only one public class or interface can show up in a source file, and the name must match the file (i.e. Test.java --> public class Test or public interface Test, but not both).


One also needs to understand interface driven programming as next step while understanding an interface. It tell what is actual use of interface. What role it plays in a Java (or any other language) program.


Yes we can write both Interface as well as public class in a same java file

interface Interfable {
public void interfMethod();

}

public class TestLam {

int x = 5;

public void testLamMethod() {
    int y = 10;
    Interfable i = () -> {
        System.out.println(x);
        System.out.println(y);
    };
    i.interfMethod();
}

public static void main(String[] args) {

    TestLam t = new TestLam();
    t.testLamMethod();
}

}

output: 5

10

// NOTE .java file name should be same as class name

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜