Multiple classes in single file

前端 未结 8 1620
北荒
北荒 2020-11-29 07:57

I\'m having trouble putting multiple classes into a single file. For example, when my file looks like:

public class FirstClass() {}
public class SecondClass(         


        
相关标签:
8条回答
  • 2020-11-29 08:14

    Yes You can write your all classes in a single .java file, But you must have only one class public(if file name and class name same)

    Example:

    class A { }

    class B { }

    class C { }

    0 讨论(0)
  • 2020-11-29 08:26

    There is no restriction on the number of class files in a java file.

    But we can’t have more than one public class per source code file. Also the name of the file must match the name of the public class. Like, a class declared as public class Dog { } must be in a source code file named Dog.java.

    And files with no public classes can have a name that does not match any of the classes in the file.

    0 讨论(0)
  • 2020-11-29 08:27

    One Java file can consist of multiple classes with the restriction that only one of them can be public. As soon as you remove public keyword from your classes, you can combine them into a single Java file.

    0 讨论(0)
  • 2020-11-29 08:29

    I see you have already done that kind of implementation. Please refer

        private class CalcButtonListener implements ActionListener
    

    in your TheaterWindow class.

    By doing this, you are creating inner classes i.e. CalcButtonListener is an inner class of TheaterWindow class. Some concept you can extend to other classes.

    0 讨论(0)
  • 2020-11-29 08:30

    I am assuming you are very beginner! Just copy paste all these contents in a single file TheaterDemo.java. And dont forget to remove all the public keyword in the beginning of class declaration.

    0 讨论(0)
  • 2020-11-29 08:31

    Just remove public from all other class definition and paste the code into TheaterDemo.java file

    public class TheaterDemo
    {
        public static void main(String[] args)
        {
            TheaterWindow theaterWindow = new TheaterWindow();
        }
    }
    //Here class code after removing public
    
    // Here another class code
    
    0 讨论(0)
提交回复
热议问题