
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can I define more than one public class in a Java package?
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 one public classes a single file a compile-time error will be generated.
Example
In the following example we have two classes Student and AccessData we are having both of them in the same class and declared both public.
import java.util.Scanner; public class Student { private String name; private int age; Student(){ this.name = "Rama"; this.age = 29; } Student(String name, int age){ this.name = name; this.age = age; } public void display() { System.out.println("name: "+this.name); System.out.println("age: "+this.age); } } public class AccessData{ public static void main(String args[]) { //Reading values from user Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); String name = sc.nextLine(); System.out.println("Enter the age of the student: "); int age = sc.nextInt(); Student obj1 = new Student(name, age); obj1.display(); Student obj2 = new Student(); obj2.display(); } }
Compile-time error
On compiling, the above program generates the following compile-time error.
AccessData.java:2: error: class Student is public, should be declared in a file named Student.java public class Student { ^ 1 error
To resolve this either you need to shift one of the classes into a separate file or,
Remove the public declaration before the class that doesn’t contain a public static void main(String args) method.
Name the file with the class name that contains main method.
In this case, remove the public before the Student class. Name the file as “AccessData.java”.
- Related Questions & Answers
- Can we declare more than one class in a single Java program?
- Can we define a package after the import statement in Java?
- Can we define a class inside a Java interface?
- How to put two public classes in a Java package.
- Can we define an interface inside a Java class?
- Can we define an enum inside a class in Java?
- How to specify that a user can enter more than one value in HTML?
- Accessing a Java class in other package.
- Add more than one shadow to a text with CSS
- How to select more than one row at a time in a JTable with Java?
- Insert more than one element at once in a C# List
- Can we define a parameterized constructor in an abstract class in Java?
- Can we define a method name same as class name in Java?
- How can I declare and define multiple variables in one statement with JavaScript?
- Delete more than one rows from a table using id in MySQL?