In Java, a class is a blueprint or template used to create objects.
It defines what data an object can store and what actions it can perform.
Java is an Object-Oriented Programming (OOP) language, and the concept of class is the foundation of Java programming.
Example
Think of a house plan.
- House plan -> Class
- Actual house built using the plan -> Object
The class does not represent a real object, but it describes how an object should look and behave.
Class Naming Rules in Java
While naming a class in Java, the following rules should be followed:
- Meaningful Name
The class name should be meaningful and clearly represent its purpose.
Example: Student, EmployeeDetails
- Starts with a Capital Letter
A class name should always start with a capital letter.
Example: StudentInfo, BankAccount
- No Spaces Allowed
Spaces are not allowed in class names.
Example:
Student Info - Not Correct
StudentInfo - Correct
- Numbers Allowed in Middle or End
Numbers can be used in the middle or at the end of a class name.
Example: Student1, Account2024
- Special Characters Not Allowed (Except _)
Special characters are not allowed in class names except underscore (_).
Example:
Student@Info - Not Correct
Student#Details - Not Correct
Student_Info - Correct
Example of a Valid Class Name
class StudentDetails1 {
}
What does a Java Class contain?
A Java class can contain:
- Variables (Fields) – to store data
- Methods – to define behavior
- Constructors – to initialize objects
- Access modifiers like public, private, etc.
Simple Java Class Example
class Student {
String name;
int age;
void study() {
System.out.println("Student is studying");
}
}
Explanation:
- Student → Class name
- name, age → Variables
- study() → Method
Creating an Object from a Class
Student s1 = new Student();
s1.name = "Arun";
s1.age = 20;
s1.study();
Here:
- s1 is an object
- It is created using the Student class
Why are Classes Important in Java?
Classes help to:
- Organize code properly
- Reuse code efficiently
- Represent real-world entities
- Follow OOP principles like encapsulation, inheritance, and polymorphism
- Without classes, Java programs cannot be written.
Conclusion
A class in Java is a template, and an object is an instance of that class.
Classes make Java programs structured, reusable, and easy to understand.
Top comments (0)