Overview

In Java, a class acts as a template to create objects and define object data types and methods.

For better understanding, let's consider an example. Imagine a class called Student that encapsulates functions like displaying the student's name and ID number. Essentially, a class provides a convenient container for managing related functions within object-oriented programming.

class Student{
   void displayName(){
   }
   void displayId() {
   }
}

Another example: A Java program with well-organized classes like Student, Score, and Subject. Each class serves a specific purpose and contains its own functions. Using classes systematically organizes code, simplifying management and maintenance. Without classes, code becomes unwieldy.

class Student{

}
class Score{

}
class Subject{

}

Number of classes and public classes

How many classes can a Java program have? Any number. Consider having class A, class B, and class C. When saving the file, any name works. For instance, Test.java can be used.

class A{

}
class B{

}
class C{

}

Save file as: Test.java

How many public classes? A Java program can contain zero or one public class. With multiple public classes, errors arise. Without a public class, any name suffices. However, a public class like C mandates naming the file C.java for proper execution.

class A{

}
class B{

}
public class C{

}

Save file as: C.java

Saving the Java file

After learning about class and public class rules, we explore naming Java files for different class types. We'll also cover potential errors if rules aren't followed.

Example – Creating classes and saving the Java file

Consider defining three classes: class A, class B, and class C. Save as Test.java. Then compile using javac. Successful compilation generates class files.

class A{

}
class B{

}
class C{

}

Save file as: Test.java

Public class name, java file name, and main class method

Understanding the connections between public class names, Java file names, and main class methods can be perplexing for many. It's crucial to note that while the public class name and Java file name share a relationship, the same cannot be said for the main class method and the Java file name. Clarifying these distinctions can help developers navigate the intricacies of Java programming with ease.

Example – Creating classes, saving, compiling, and running the code

In this scenario, we have four classes: A, B, C, and D. A, B, and C have public static void main methods. D has no methods.

class A{
  public static void main (String[] args){
    System.out.println("This is main class A");
  }
}
class B{
  public static void main (String[] args){
    System.out.println("This is main class B");
  }
}
class C{
  public static void main (String[] args){
    System.out.println("This is main class C");
  }
}
class D{
}

End Of Article

End Of Article