Multiple classes in single file

java multiple classes with main
java multiple classes in one package
java multiple classes in one file example
android multiple classes in one file
multiple classes in java
multiple classes can be written in a single java file
why only one public class in java file
code with multiple classes

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

public class FirstClass() {}
public class SecondClass() {}
public class ThirdClass() {}

I get an error during compilation. I'm not quite sure what's causing this. Any ideas?

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.

Java: Multiple class declarations in one file, And even if we declare multiple classes in a single source file (.java), still each class will have its own class file after compilation. But the fact is  Coming from a C++ background I've grown accustomed to organizing my classes such that, for the most part, there's a 1:1 ratio between classes and files. By making it so that a single file contains a single class I find the code more navigable. As I introduce myself to Python I'm finding lots of examples where a single file contains multiple classes.

At the risk of spoon-feeding

Please read http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class TheaterWindow extends JFrame
{
    private JPanel pnlAdultTicketPrice, pnlAdultTicketsSold, pnlChildTicketPrice, pnlChildTicketsSold,
        pnlCalculate, pnlMain;
    private JLabel lblAdultTicketPrice, lblAdultTicketsSold, lblChildTicketPrice, lblChildTicketsSold;
    private JTextField txtAdultTicketPrice, txtAdultTicketsSold, txtChildTicketPrice, txtChildTicketsSold;
    private JButton btnCalculate;

    public TheaterWindow()
    {
        // Sets window title
        setTitle("Theater");

        // Sets layout to BorderLayout
        setLayout(new GridLayout(5,1));

        // Specifies what happens when close button is clicked
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Builds the panels
        buildPanels();

        // Add the panels to the frame's content pane
        add(pnlAdultTicketPrice);
        add(pnlChildTicketPrice);
        add(pnlAdultTicketsSold);
        add(pnlChildTicketsSold);
        add(pnlCalculate);

        // Size the frame to fit all of the panels
        pack();

        // Display the window
        setVisible(true);
    }

    private void buildPanels()
    {
        // Creates labels to display instructions
        lblAdultTicketPrice = new JLabel("Adult ticket price");
        lblChildTicketPrice = new JLabel("Child ticket price");
        lblAdultTicketsSold = new JLabel("Adult tickets sold");
        lblChildTicketsSold = new JLabel("Child tickets sold");

        // Creates text fields that are 10 characters wide
        txtAdultTicketPrice = new JTextField(10);
        txtChildTicketPrice = new JTextField(10);
        txtAdultTicketsSold = new JTextField(10);
        txtChildTicketsSold = new JTextField(10);

        // Creates button with caption
        btnCalculate = new JButton("Calculate");

        // Adds action listener to button
        btnCalculate.addActionListener(new CalcButtonListener());

        // Creates panels
        pnlAdultTicketPrice = new JPanel();
        pnlChildTicketPrice = new JPanel();
        pnlAdultTicketsSold = new JPanel();
        pnlChildTicketsSold = new JPanel();
        pnlCalculate = new JPanel();
        pnlMain = new JPanel();

        // Adds elements to their proper panels
        pnlAdultTicketPrice.add(lblAdultTicketPrice);
        pnlAdultTicketPrice.add(txtAdultTicketPrice);
        pnlChildTicketPrice.add(lblChildTicketPrice);
        pnlChildTicketPrice.add(txtChildTicketPrice);
        pnlAdultTicketsSold.add(lblAdultTicketsSold);
        pnlAdultTicketsSold.add(txtAdultTicketsSold);
        pnlChildTicketsSold.add(lblChildTicketsSold);
        pnlChildTicketsSold.add(txtChildTicketsSold);
        pnlCalculate.add(btnCalculate);

        // Adds all of the above panels to a main panel
        pnlMain.add(pnlAdultTicketPrice);
        pnlMain.add(pnlChildTicketPrice);
        pnlMain.add(pnlAdultTicketsSold);
        pnlMain.add(pnlChildTicketsSold);
        pnlMain.add(pnlCalculate);
    }

    private class CalcButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            // Creates object of Theater
            Theater theater = new Theater();

            // Sets the member variables of Theater to the user's input
            theater.setAdultTicketPrice(Double.parseDouble(txtAdultTicketPrice.getText()));
            theater.setChildTicketPrice(Double.parseDouble(txtChildTicketPrice.getText()));
            theater.setAdultTicketsSold(Integer.parseInt(txtAdultTicketsSold.getText()));
            theater.setChildTicketsSold(Integer.parseInt(txtChildTicketsSold.getText()));

            // Creates DecimalFormat object for rounding
            DecimalFormat dollar = new DecimalFormat("#.##");

            // Display the charges.
            JOptionPane.showMessageDialog(null, "Adult ticket gross: $" +
                    Double.valueOf(dollar.format(theater.getAdultGross())) + "\n" +
                    "Child ticket gross: $" + Double.valueOf(dollar.format(theater.getChildGross())) + "\n" +
                    "Adult ticket net: $" + Double.valueOf(dollar.format(theater.getAdultNet())) + "\n" +
                    "Child ticket net: $" + Double.valueOf(dollar.format(theater.getChildNet())) + "\n" +
                    "Total gross: $" + Double.valueOf(dollar.format(theater.getChildGross())) + "\n" +
                    "Total net: $" + Double.valueOf(dollar.format(theater.getTotalNet())));
        }
    }

    public class Theater
    {
        private double PERCENTAGE_KEPT = 0.20;

        private double adultTicketPrice, childTicketPrice;
        private int adultTicketsSold, childTicketsSold;

        public double getAdultGross()
        {
            return getAdultTicketPrice() * getAdultTicketsSold();
        }

        public double getAdultNet()
        {
            return PERCENTAGE_KEPT * getAdultGross();
        }

        public double getAdultTicketPrice()
        {
            return adultTicketPrice;
        }

        public int getAdultTicketsSold()
        {
            return adultTicketsSold;
        }

        public double getChildGross()
        {
            return getChildTicketPrice() * getChildTicketsSold();
        }

        public double getChildNet()
        {
            return PERCENTAGE_KEPT * getChildGross();
        }

        public double getChildTicketPrice()
        {
            return childTicketPrice;
        }

        public int getChildTicketsSold()
        {
            return childTicketsSold;
        }

        public double getTotalGross()
        {
            return getChildGross() + getAdultGross();
        }

        public double getTotalNet()
        {
            return getChildGross() + getChildNet();
        }

        public void setAdultTicketPrice(double adultTicketPrice)
        {
            this.adultTicketPrice = adultTicketPrice;
        }

        public void setAdultTicketsSold(int adultTicketsSold)
        {
            this.adultTicketsSold = adultTicketsSold;
        }

        public void setChildTicketPrice(double childTicketPrice)
        {
            this.childTicketPrice = childTicketPrice;
        }

        public void setChildTicketsSold(int childTicketsSold)
        {
            this.childTicketsSold = childTicketsSold;
        }
    }
}

Why a Single Java Source File Can Not Have More Than One Public , Two Ways of Implementing Multiple Classes in a single Java When we compile the above program, two .class files will be created which are  As for performance, you really shouldn't have 5000 classes in a single project. If you do, some refactoring might be in order. That said, there are instances when we have multiple classes in one file. And that is when it's just a private helper class for the main class of the file.

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

Can we declare more than one class in a single Java program?, No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public. If you have more than  In Java, you can define multiple top level classes in a single file, providing that at most one of these is public (see JLS §7.6). See below for example. See below for example. Is there a tidy name for this technique (analogous to inner , nested , anonymous )?

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.

Can I define more than one public class in a Java package?, My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a  When multiple classes are stricly related, more than one class in the same source file is, IMHO, BETTER than dedicating a short source file to each class. The source is more readable and compact (and using #region the same source can be be more structured than before).

Learn Java Programming, Java: Multiple class declarations in one file. If you already know why the following code fail to compile, then you don't need to continue reading! In short, the number of.class files created will be equal to the number of classes in the code. We can create as many classes as we want but writing many classes in a single file is not recommended as it makes code difficult to read rather we can create a single file for every class.

Java: Multiple class declarations in one file, You can create as many classes as you want, but writing many classes in a single file isn't recommended, as it makes code difficult to read. Instead, you can​  In Java, you can place as many classes as you like inside of a single source code file. However, there can be only one public class per source code file and the class declaration name must match

Java: Multiple class declarations in one file – SkynetComputing, If your concrete implementations have very different internal concerns, your single file accumulates all those concerns. For example, implementations with  In a nutshell number of.class files created are equal to the number of classes in the program. You can create as many classes as you want, but writing many classes in a single file isn't recommended, as it makes code difficult to read. Instead, you can create a separate file for every class.

Using multiple classes in a Java program,

Comments
  • stackoverflow.com/questions/4651568/…
  • "My professor asked us to turn in our assignments in a single .class file to save him time." - Your professor is encouraging bad habits and should know better ...
  • @rini - that Q&A is about packages ... not about combining multiple classes into one ".java" file.
  • Most of the answers implicitly address only multiple top-level classes per file. You can have multiple public classes defined in a single file -- just not multiple top-level classes. Five years after this question was posted, I've added a correct, more complete answer.
  • "with the restriction that only one of them can be public"...I don't think so. Take a look at Rectangle2D for example, it has two inner class, both are public...
  • @MadProgrammer : rectangle 2d does not contain a main function. If you have a main function in a class that function should be declared as public and the file should have the name of that public class. But if there is not main(), then you can have any number of classes as public, The OP's class theaterdemo contains main().
  • It makes no difference, you can have as many public inner classes as you like, they can even be static, but yes, the outer class containing the main method should public.
  • Thanks for the brief but comprehensive answer.
  • @Ashwin And of course someone's edited the question just to remove that very important bit of info...
  • Yes, but why? and what does that say about the visibility and scope of the other classes b and c?