Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two public classes in one file java

Tags:

java

Ok, this might be kiddies question in java. We can't define two public classes in one file. But, in one of the examples from the book SCJP study guide, this example was mentioned:

public abstract class A{
    public abstract void show(String data);
}

public class B extends A{
    public void show(String data){
        System.out.println("The string data is "+data);
    }
    public static void main(String [] args){
        B b = new B();
        b.show("Some sample string data");
    }
}

When I copy pasted this into netbeans immediately compile error was thrown, that public class A should me mentioned in separate file. Is that example from SCJP styudy guide really wrong? Also in some of the mock test I found many questions having such pattern but in none of the options was a compiler error was mentioned. Getting worried here

like image 954
Shades88 Avatar asked Jun 24 '12 13:06

Shades88


2 Answers

yes, 2 top level public classes are not allowed in one file

like image 96
Tom Avatar answered Sep 29 '22 00:09

Tom


Well, if one is being so picky: you can have multiple classes defined with a public modifier in the same file, that is, using the static nested(inner) class. like this:

File -> Test.java

public class Test {

    public static class SomeNestedClass {

    }

}
like image 34
a.u.r Avatar answered Sep 29 '22 00:09

a.u.r