Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple classes in java in one file?

Tags:

java

I want to know how to use multiple classes in one file in java. I typed this code but it is showing compilation errors.

class test {

    int a, b, c;

    void getdata(int x, int y) {
        a = x;
        b = y;
    }

    void add() {
        c = a + b;
        System.out.println("Addition = " + c);
    }
}

public class P8 {

    public static void main(String[] args) {

        test obj = new test();
        test.getdata(200, 100);
        test.add();
    }
}
like image 859
Sheikh Rasik Avatar asked Sep 13 '25 12:09

Sheikh Rasik


1 Answers

You can only have one public top-level class per file. So, remove the public from all but one (or all) of the classes.

However, there are some surprising problems that can happen if you have multiple classes in a file. Basically, you can get into trouble by (accidentally or otherwise) defining multiple classes with the same name in the same package.

If you're just a beginner, it might be hard to imagine what I'm going on about. The simple rule to avoid the problems is: one class per file, and call the file the same thing as the class it declares.

like image 175
Andy Turner Avatar answered Sep 15 '25 02:09

Andy Turner