Tutorials Logic, IN info@tutorialslogic.com

Classes and Objects in Java: Detailed Notes, Syntax, Examples & FAQs

Classes and Objects in Java

A class in Java is a blueprint that defines what an object should contain and what it should be able to do. It groups related data and behavior in one named type.

An object is a real instance of a class created at runtime. Each object has its own field values, can call methods, and is accessed through a reference variable.

Classes and objects are the base of object-oriented programming in Java. Once this topic is clear, constructors, encapsulation, inheritance, polymorphism, interfaces, and collections become much easier to understand.

Mental Model

Think of a class as a design for a student record, bank account, car, product, or employee. An object is one actual student, one actual account, one actual car, one actual product, or one actual employee created from that design.

What Is a Class in Java?

A class is a user-defined type. It can contain fields, methods, constructors, nested classes, initializer blocks, and constants. For beginners, the most important parts are fields, methods, and constructors.

Fields store state. Methods define behavior. Constructors prepare a new object when it is created. The class name should usually be a noun written in PascalCase, such as Student, BankAccount, Product, or Employee.

Part Meaning Example
Class Blueprint or custom type Student
Field Data stored inside an object name
Method Behavior or action display()
Object Runtime instance of a class new Student()
  • A class does not automatically represent real data until an object is created.
  • A Java source file can contain multiple classes, but only one public top-level class should match the file name.
  • Classes help organize large programs into smaller reusable units.

Basic Class Syntax

Basic Class Syntax
class Student {
    int rollNo;
    String name;

    void display() {
        System.out.println(rollNo + " - " + name);
    }
}
  • Student is the class name.
  • rollNo and name are fields.
  • display() is a method that uses object state.

What Is an Object in Java?

An object is created from a class using the new keyword. The object gets memory for its instance fields, and Java returns a reference that can be stored in a variable.

The object reference is used with the dot operator to read fields, update fields, and call methods. Different objects of the same class can hold different values.

  • The new keyword creates an object.
  • The dot operator accesses members of an object.
  • Each object has its own copy of instance fields.

Creating and Using Objects

Creating and Using Objects
class Student {
    int rollNo;
    String name;

    void display() {
        System.out.println(rollNo + " - " + name);
    }
}

public class StudentDemo {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.rollNo = 101;
        s1.name = "Asha";

        Student s2 = new Student();
        s2.rollNo = 102;
        s2.name = "Ravi";

        s1.display();
        s2.display();
    }
}
  • s1 and s2 are reference variables.
  • Both objects use the same class but store different field values.
  • Calling display() on each object prints that object's state.

Class vs Object

Beginners often mix up class and object. The class is the design. The object is the actual runtime instance created from the design.

You write a class once, then create as many objects as needed. For example, one BankAccount class can create many customer account objects.

Class Object
Blueprint or template Actual instance
Declared with class keyword Created with new keyword
Does not hold unique runtime state by itself Holds field values for one instance
Example: class Car Example: Car car1 = new Car();
Loaded as type information Allocated as instance data

Fields and Methods

Fields are variables declared inside a class. Instance fields belong to each object. Static fields belong to the class itself and are shared.

Methods are functions declared inside a class. Instance methods usually work with object state. Static methods belong to the class and do not need an object.

  • Use fields for data that describes the object.
  • Use methods for behavior that should happen through the object.
  • Avoid making fields public in real projects; use private fields with methods once encapsulation is introduced.

Fields and Methods Together

Fields and Methods Together
class BankAccount {
    String accountHolder;
    double balance;

    void deposit(double amount) {
        balance = balance + amount;
    }

    void withdraw(double amount) {
        if (amount <= balance) {
            balance = balance - amount;
        }
    }

    void printBalance() {
        System.out.println(accountHolder + " balance: " + balance);
    }
}

Constructors

A constructor is a special block that runs when an object is created. It has the same name as the class and no return type.

Constructors are commonly used to initialize required fields. If no constructor is written, Java provides a default no-argument constructor. Once you write any constructor, Java does not automatically provide the default constructor.

  • Constructor name must match the class name.
  • Constructor does not have a return type, not even void.
  • Constructors can be overloaded with different parameter lists.

Constructor Example

Constructor Example
class Product {
    String name;
    double price;

    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    void printDetails() {
        System.out.println(name + " costs " + price);
    }
}

public class ProductDemo {
    public static void main(String[] args) {
        Product laptop = new Product("Laptop", 55000);
        laptop.printDetails();
    }
}
  • new Product(...) creates the object and calls the constructor.
  • this.name means the field of the current object.
  • name without this is the constructor parameter.

this Keyword

The this keyword refers to the current object. It is commonly used when field names and parameter names are the same.

this can also call another constructor in the same class using this(...), but that call must be the first statement inside the constructor.

  • Use this.fieldName to make object fields clear.
  • Use this(...) for constructor chaining.
  • Do not use this inside a static method because static methods do not belong to one object.

Using this

Using this
class Employee {
    int id;
    String name;

    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    void print() {
        System.out.println(this.id + " - " + this.name);
    }
}

Object References and Memory Basics

In Java, an object variable stores a reference to an object, not the object itself. The object is created in heap memory, while the reference variable points to it.

If two reference variables point to the same object, a change through one reference is visible through the other. If two references point to two separate objects with the same values, == still returns false because the identities are different.

Reference Behavior

Reference Behavior
class Counter {
    int value;
}

public class ReferenceDemo {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        c1.value = 5;

        Counter c2 = c1;
        c2.value = 10;

        System.out.println(c1.value); // 10
        System.out.println(c1 == c2); // true
    }
}
  • c1 and c2 point to the same object.
  • Changing c2.value changes the same object seen by c1.
  • == checks whether both references point to the same object.

Static Members vs Instance Members

Instance fields and methods belong to objects. Static fields and methods belong to the class.

Use static for shared data or utility behavior that does not require object state. Do not make everything static just to avoid creating objects, because that defeats the purpose of object-oriented design.

Member Type Belongs To Access Example
Instance field Each object student.studentName
Instance method Each object student.printStudent()
Static field Class Student.schoolName
Static method Class Math.max(10, 20)

Static and Instance Members

Static and Instance Members
class Student {
    static String schoolName = "City Public School";
    String studentName;

    Student(String studentName) {
        this.studentName = studentName;
    }

    void printStudent() {
        System.out.println(studentName + " studies at " + schoolName);
    }
}

Complete Practice Example

This example combines class syntax, private fields, constructor initialization, methods, this keyword, and object creation.

Bank Account Class

Bank Account Class
class BankAccount {
    private String accountNumber;
    private String holderName;
    private double balance;

    BankAccount(String accountNumber, String holderName, double openingBalance) {
        this.accountNumber = accountNumber;
        this.holderName = holderName;
        this.balance = openingBalance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }

    void printStatement() {
        System.out.println(accountNumber + " | " + holderName + " | " + balance);
    }
}

public class BankAccountDemo {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("A101", "Neha", 5000);
        account.deposit(1500);
        account.withdraw(700);
        account.printStatement();
    }
}
Key Takeaways
  • I can explain the difference between a class and an object.
  • I can write a Java class with fields and methods.
  • I can create objects using new and access members using the dot operator.
  • I can write a constructor and use this to initialize fields.
  • I can explain object references and why == compares identity.
  • I can identify when a member should be instance or static.
Common Mistakes to Avoid
WRONG Writing all code inside main
RIGHT Create classes that represent real concepts and move behavior into methods
main should start the program; classes should model the work.
WRONG Adding void before a constructor
RIGHT Write a constructor with no return type
If you write void, it becomes a method, not a constructor.
WRONG Comparing object content with ==
RIGHT Use equals() when content equality is needed
== compares whether references point to the same object.
WRONG Making every field public
RIGHT Use private fields and controlled methods in real code
Public fields allow uncontrolled changes and make maintenance harder.
WRONG Making everything static
RIGHT Use instance members when behavior depends on object state
Objects are useful because each instance can hold different state.

Practice Tasks

  • Create a Student class with rollNo, name, marks, and a method that prints pass or fail.
  • Create a Product class with name, price, quantity, and a method that calculates total amount.
  • Create two objects of the same class and prove that changing one object does not change the other.
  • Create two references pointing to the same object and observe how changes are shared.
  • Rewrite a procedural bank balance program using a BankAccount class.

Frequently Asked Questions

A class is a blueprint or user-defined type that defines fields, constructors, and methods for objects.

An object is a runtime instance of a class. It has its own state and can call methods defined by the class.

A class is the design. An object is the actual instance created from that design using new.

Yes. One class can be used to create many objects, and each object can hold different instance field values.

Constructors initialize new objects and help ensure required fields are set when the object is created.

<code>this</code> refers to the current object. It is often used to distinguish object fields from method or constructor parameters.

Objects are created in heap memory. Reference variables point to those objects.

Java is pass by value. When an object is passed to a method, the value copied is the object reference.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.