YoungerDryas
YoungerDryas

Reputation: 114

Java - How to include 2 classes in the same file?

I am trying to Include two or more classes in one file, but java just throws this error message at me! How would I include 2 or more classed in 1 file?

Exception in thread "main" java.lang.ExceptionInInitializerError
    at javaapp.main(javaapp.java:25)
Caused by: java.lang.RuntimeException: Uncompilable source code - class functions1 is public, should be declared in a file named functions1.java
    at functions1.<clinit>(javaapp.java:11)
    ... 1 more
Java Result: 1



public class functions1 {
    public String Print(String text){
        System.out.println(text);
        return text;
    }
}

public class javaapp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        functions1 Func = new functions1();
        Func.Print("You're learning Java!!!!!");


    }

}

Upvotes: 0

Views: 1030

Answers (3)

Ashik Ali
Ashik Ali

Reputation: 11

Sir you should use inner class it is a better option where you can access you class fields privately and your class code will be separate

Upvotes: -1

Sai Ye Yan Naing Aye
Sai Ye Yan Naing Aye

Reputation: 6738

Juned Ahsan's answer is right but if you want use 2 classes in the same file, you have one option.Use inner class. Check this sample

public class OuterClass {
    int outerVariable = 100;

    class InnerClass {
        int innerVariable = 20;

        int someMethod(int parameter) {
           //Do something.
        }       
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        InnerClass inner = outer.new InnerClass(); 
        System.out.println(inner.someMethod(3));
    }
}

And also check this from oracle.

Upvotes: 3

Juned Ahsan
Juned Ahsan

Reputation: 68715

You can only have one public class in a compilation unit or .java file. Your code should give the desired output if you just take the public specifier out of your functions1 class

public class functions1 {

convert to

class functions1 {

Upvotes: 1

Related Questions