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.

  1. Class: Blueprint or template for creating objects
  2. Object: Instance of a class

1. Defining a Class

  1. 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

  1. Use the new keyword 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

  1. A class is a blueprint
  2. An object is a real-world instance of the class
  3. Multiple objects can be created from the same class
  4. 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

  1. Class → blueprint for objects
  2. Object → instance of a class
  3. Fields → define attributes
  4. Methods → define behavior
  5. Java is object-oriented, allowing modular and reusable code