• Register
1 vote


I have a very basic question being a novice. It might be silly to you but I really want to know the fact.

Let’s say you have a java program. Can you have two classes in one java file?

What is the reason behind it? Thanks for your clearance.

12 7 7
15,250 points

1 Answer

1 vote


Yes, we can. All we have to do is make sure that only one of them is public. A java file can’t run without a public class.

The below example will help you to understand it well. If you still have any questions, just reply to this thread.

public class MyTestClass {
  int a = 5;
class MyOtherClass {
  public static void main(String[] args) {
    MyTestClass myOb = new MyTestClass();


13 9 6
94,240 points

Related questions

0 votes
1 answer 655 views
Problem : Getting below eclipse error the class file viewer cannot handle the given input ('org.eclipse.ui.ide.filestoreeditorinput').
asked Nov 12, 2019 peterlaw 6.9k points
0 votes
1 answer 40 views
Problem : I have following two classes: JDialog and JFrame (see signature below). I want them to have few extra methods, but I also want them both to extend my code, without rewriting the code Is it possible to do that? java.awt.Window java.awt.Dialog javax.swing. ... the identical way. So I will not want to write the code twice. I want only one class to utilize the code of the other class.
asked Dec 7, 2019 alecxe 7.5k points
0 votes
1 answer 16 views
I have created a Person class with two attributes, age and name, and later I have implemented a vector of people to try to print the attributes of the objects entered there. When I try to access the age attribute, there is no problem and it prints the values to me, but when trying to access ... people_vector.begin ();   while (it! = vector_people.end ())   {     it-> getName ();     it ++;   } }
asked Aug 15 game 4.6k points
0 votes
1 answer 5 views
I want a program that will help me to copy one file to another file in Java.
asked Sep 22 Daniel Anderson 4k points
0 votes
1 answer 1.1K views
Problem : I am currently working on the project and i am getting the error as below : "Implicit super constructor MyPerson() is undefined. Must explicitly invoke another constructor" But I am unable to understand it. Below is my MyPerson class: public class ... and just giving it an instructor variable as below : public class MyStudent extends MyPerson { public MyStudent(String myInstructor) { } }
asked Dec 16, 2019 alecxe 7.5k points