Start Coding Now

Classes and Objects in Java - OOP Fundamentals

Learn about classes and objects in Java. Understand OOP fundamentals with practical examples and best practices.

Introduction

Classes and objects are the core concepts of Object-Oriented Programming (OOP) in Java. A class is a blueprint, and an object is an instance of that blueprint.

Defining a Class

public class Student {
    // Fields (attributes)
    String name;
    int age;
    String grade;
    
    // Method (behavior)
    void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Grade: " + grade);
    }
    
    void study(String subject) {
        System.out.println(name + " is studying " + subject);
    }
}

Creating Objects

public class Main {
    public static void main(String[] args) {
        // Create objects
        Student student1 = new Student();
        Student student2 = new Student();
        
        // Set field values
        student1.name = "Rahul";
        student1.age = 20;
        student1.grade = "A";
        
        student2.name = "Priya";
        student2.age = 19;
        student2.grade = "A+";
        
        // Call methods
        student1.displayInfo();
        student1.study("Java Programming");
        
        System.out.println();
        
        student2.displayInfo();
        student2.study("Data Structures");
    }
}

Class with Constructor

public class Car {
    String brand;
    String model;
    int year;
    
    // Constructor
    Car(String brand, String model, int year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }
    
    void displayDetails() {
        System.out.println(year + " " + brand + " " + model);
    }
}

public class Main { public static void main(String[] args) { Car car1 = new Car("Toyota", "Camry", 2023); Car car2 = new Car("Honda", "Civic", 2022); car1.displayDetails(); car2.displayDetails(); } }

Summary

  • Classes are blueprints for objects
  • Objects are instances of classes
  • Fields store object state
  • Methods define object behavior
  • Constructors initialize objects

Frequently Asked Questions

What is a class in Java?

A class is a blueprint or template for creating objects. It defines the properties (fields) and behaviors (methods) that objects of that type will have.

What is an object in Java?

An object is an instance of a class. It is a real-world entity that has state (fields) and behavior (methods) as defined by its class.