Java Classes and Objects – Complete Guide with Examples
Learn Object-Oriented Programming in Java by understanding classes, objects, and their usage with detailed examples, syntax, and best practices.
Classes and Objects in Java – Complete Detailed Tutorial
Java is a fully object-oriented language, which means everything revolves around objects and classes.
- Class: Blueprint or template for creating objects
- Object: Instance of a class
1. Defining a Class
- A class contains fields (variables) and methods (functions)
Syntax:
class ClassName {
// fields (variables)
// methods (functions)
}
Example:
class Student {
String name;
int age;
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
2. Creating Objects
- Use the
newkeyword to create an object
Syntax:
ClassName obj = new ClassName();
Example:
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "John";
s1.age = 20;
s1.display();
}
}
Output:
Name: John
Age: 20
3. Key Points
- A class is a blueprint
- An object is a real-world instance of the class
- Multiple objects can be created from the same class
- Fields store object state, methods define behavior
4. Example – Multiple Objects
class Car {
String brand;
int year;
void showDetails() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.brand = "Toyota";
car1.year = 2020;
car1.showDetails();
Car car2 = new Car();
car2.brand = "Honda";
car2.year = 2022;
car2.showDetails();
}
}
Output:
Brand: Toyota, Year: 2020
Brand: Honda, Year: 2022
5. Summary
- Class → blueprint for objects
- Object → instance of a class
- Fields → define attributes
- Methods → define behavior
- Java is object-oriented, allowing modular and reusable code