⚡0 XP🔥0

Classes and Objects

Lesson 9 of 15 ⏱ 7 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs Java

Define classes with fields and methods, create objects with new, constructors and overloading, this, access modifiers, encapsulation with getters/setters, static members and toString.

Java is an object-oriented language: you model a program as objects that have state (fields) and behaviour (methods). A class is the blueprint; an object is a concrete instance made from it.

हिंदी में समझें

Class एक नक्शा है (जैसे "Car" का design) और object उस नक्शे से बनी असली चीज़ (आपकी लाल Swift, मेरी सफ़ेद Nexon)। हर object का अपना data (रंग, नंबर) होता है, पर काम (methods - चलाना, ब्रेक लगाना) सबके एक जैसे होते हैं।

A first class#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
Red Swift at 60 km/h
White Nexon at 65 km/h
Red Swift at 0 km/h

new Car() creates an object on the heap; a and b hold references to two different objects.

Note

In the editor here, extra classes like Car are written in the same file without public. In a real project, each public class goes in its own file (Car.java).

Constructors#

A constructor runs automatically when an object is created and sets up its initial state. It has the same name as the class and no return type:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
Mouse - Rs 499.0 (0 in stock)
Keyboard - Rs 1299.0 (15 in stock)
  • Overloaded constructors offer different ways to create objects.
  • this.field refers to the current object's field (needed when a parameter has the same name).
  • this(...) calls another constructor of the same class (must be the first statement).
  • If you write no constructor, Java provides a default empty one.

Access modifiers and encapsulation#

Modifier Class Package Subclass Everywhere
private ✓
(default) ✓ ✓
protected ✓ ✓ ✓
public ✓ ✓ ✓ ✓

Encapsulation = make fields private and expose controlled public methods (getters/setters) that can validate data:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
Farah earns 83600.0
Invalid salary for Farah, keeping 83600.0

toString, equals and object references#

Every class inherits from Object. Overriding toString() controls how the object prints:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
a = (2, 3)
a == b: false
a.equals(b): true
a == c: true
Tip

If you override equals, also override hashCode - HashMap and HashSet depend on both being consistent.

static members#

A static field is shared by all objects of the class; a static method belongs to the class and is called as ClassName.method():

▶ Try it YourselfJava
Ctrl + Enter to run
Output
Order#1 Rs 499.0
Order#2 Rs 1299.5
Order#3 Rs 250.0
3 orders, sales Rs 2048.5

A static method cannot use instance fields directly (there is no this) - that is why main cannot touch non-static fields without creating an object.

Records - compact data classes (Java 16+)#

For classes that only carry data, a record generates the constructor, getters, equals, hashCode and toString for you:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
Course[code=CS202, title=Java Programming, credits=4]
Java Programming has 4 credits
true

Summary#

  • A class defines fields and methods; new creates objects; variables hold references.
  • Constructors initialise objects; overload them and chain with this(...).
  • Encapsulation: private fields + validated public getters/setters.
  • Override toString (and equals/hashCode together); static members are shared by the class.
  • record creates immutable data classes in one line.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

BankAccount with encapsulation

Complete BankAccount with a private balance, deposit(double) (ignore amounts <= 0), withdraw(double) that returns false if the amount is more than the balance, and getBalance(). The given main must print:

Balance: 7500.0
Withdraw 10000: false
Withdraw 2500: true
Balance: 5000.0
Expected output:
Balance: 7500.0
Withdraw 10000: false
Withdraw 2500: true
Balance: 5000.0
2

Student with toString and a static counter

Give Student a constructor (String name, double cgpa), an auto-generated roll number starting at 1001 (use a static counter), and toString() returning 1001: Asha (8.7). Print three students and Total students: 3.

Expected output:
1001: Asha (8.7)
1002: Ravi (7.9)
1003: Imran (9.2)
Total students: 3

Quick Quiz

Q1.

What does new Student() do?

Q2.

If you write no constructor at all, Java...

Q3.

Which access modifier makes a member visible only inside its own class?

Q4.

What does this(...) as the first line of a constructor do?

Q5.

Why override toString()?