Class in Java::
Source: Dev.to
Class
Definition
A class is a blueprint or template used to create objects. It defines the properties (variables) and behaviors (methods) that the objects created from it will have.
Declaration
A class must be declared using the class keyword.
class MyClass {
}
Naming Rules
- The class name must start with a letter (
A–Zora–z). - It cannot start with a digit.
- It must not contain spaces.
- Only the characters
_and$are allowed as special characters. - Java reserved keywords cannot be used as class names.
- By convention, the class name should start with a capital letter, and if it contains multiple words, each word should start with a capital letter.
class StudentDetails
Body and Structure
The body of a class must be enclosed within curly braces {}.
class Car {
// fields and methods
}
File Naming
- A
.javafile can contain only one public class. - If a class is declared as
public, the file name must match the public class name.
public class Student {
}
Access Modifiers
- A class can have an access modifier such as
public, or no modifier (default package‑private). - Top‑level classes cannot be
privateorprotected.
Main Method
To execute a Java program, the class must contain the main() method.
public static void main(String[] args) {
// program entry point
}
Multiple Classes in One File
Multiple classes can be defined in a single file, but only one of them may be declared public.