Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 9 of 20 · 5 min read

Java classes and objects

Java classes and objects notes with examples: fields and methods, creating objects with new, constructors and overloading, this, toString and references.

Object-oriented programming

Java is an object-oriented language: a program is a set of objects that work together. A library system has Book, Member and Loan objects; a bank app has Account and Customer objects.

  • A class is a blueprint: it says what data an object holds and what it can do.
  • An object is one real thing built from that blueprint. One Student class can create thousands of student objects.

A first class

public class Student {
    // fields: the data each object holds
    String name;
    int rollNo;
    double marks;

    // a method: what the object can do
    void show() {
        System.out.println(rollNo + " " + name + " " + marks);
    }
}

Creating objects with new

public class School {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Asha";
        s1.rollNo = 1;
        s1.marks = 88.5;

        Student s2 = new Student();
        s2.name = "Ravi";
        s2.rollNo = 2;
        s2.marks = 76;

        s1.show();   // 1 Asha 88.5
        s2.show();   // 2 Ravi 76.0
    }
}
  • new Student() creates an object in memory (on the heap).
  • s1 is a reference variable: it holds the address of the object, not the object itself.
  • The dot operator . reaches the object's fields and methods.
  • Each object has its own copy of the fields: changing s1.name does not affect s2.

Fields get default values (0, 0.0, false, null) if you do not set them.

Constructors

A constructor sets up a new object. It has the same name as the class and no return type. It runs automatically when you call new.

public class Student {
    String name;
    int rollNo;
    double marks;

    Student(String name, int rollNo, double marks) {
        this.name = name;
        this.rollNo = rollNo;
        this.marks = marks;
    }

    void show() {
        System.out.println(rollNo + " " + name + " " + marks);
    }
}

// now one line creates a ready object:
Student s1 = new Student("Asha", 1, 88.5);

The default constructor

If you write no constructor, Java adds an empty one: Student() { }. As soon as you write any constructor, that free one disappears, so new Student() stops compiling unless you add it back.

Overloaded constructors and this(...)

public class Account {
    String holder;
    double balance;

    Account(String holder) {
        this(holder, 0);              // calls the other constructor
    }

    Account(String holder, double opening) {
        this.holder = holder;
        this.balance = opening;
    }
}

this(...) must be the first statement in a constructor.

The this keyword

this means "the current object". Use it to:

  • tell a field from a parameter with the same name: this.name = name;
  • call another constructor: this(holder, 0);
  • pass the current object to another method: register(this);

Methods that use and change fields

public class Account {
    String holder;
    double balance;

    Account(String holder, double opening) {
        this.holder = holder;
        this.balance = opening;
    }

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

    boolean withdraw(double amount) {
        if (amount > balance) return false;
        balance -= amount;
        return true;
    }
}
Account a = new Account("Meena", 1000);
a.deposit(500);
System.out.println(a.withdraw(2000));   // false
System.out.println(a.balance);          // 1500.0

toString: a readable object

Printing an object shows something like Student@6d06d69c unless the class defines toString():

@Override
public String toString() {
    return "Student[" + rollNo + ", " + name + ", " + marks + "]";
}

Now System.out.println(s1); prints Student[1, Asha, 88.5].

References and null

Student a = new Student("Asha", 1, 88.5);
Student b = a;            // b refers to the same object
b.marks = 95;
System.out.println(a.marks);   // 95.0

Student c = null;         // refers to no object
// c.show();              // NullPointerException

An object that no variable refers to any more is cleaned up by the garbage collector.

Arrays of objects

Student[] cls = {
    new Student("Asha", 1, 88.5),
    new Student("Ravi", 2, 76),
    new Student("Meena", 3, 91)
};
for (Student s : cls) s.show();

Common mistakes

  • Giving a constructor a return type: void Student(...) is a normal method, not a constructor.
  • Writing name = name; in a constructor: it assigns the parameter to itself. Use this.name = name;.
  • Declaring Student s; and using it before s = new Student(...).
  • Adding a constructor with parameters and then calling new Student() that no longer exists.
  • Expecting b = a to copy an object; it copies the reference.

Key points

  • A class is a blueprint; an object is an instance created with new.
  • Fields hold each object's data; methods define its behaviour.
  • A constructor has the class name and no return type; it runs on new.
  • this refers to the current object; this(...) calls another constructor.
  • Override toString() to print objects nicely.
  • Variables of class types hold references; null means no object.

Practice questions

1. What is the difference between a class and an object?

A class is the design (fields and methods). An object is one instance made from it with new, with its own field values.

2. Write a Rectangle class with length and width, a constructor, and an area() method.
public class Rectangle {
    double length, width;

    Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    double area() {
        return length * width;
    }
}
3. Why does new Book() fail when the class only has Book(String title)?

Java adds a default no-argument constructor only when the class has no constructor at all. Once Book(String) exists, a no-argument constructor must be written by hand.

4. What does this print? Account x = new Account("A", 100); Account y = x; y.deposit(50); System.out.println(x.balance);

150.0. x and y refer to the same object.

5. Add a toString() to Rectangle that returns, for example, Rectangle 4.0 x 3.0.
@Override
public String toString() {
    return "Rectangle " + length + " x " + width;
}