Beginner · Classes and objects · topic 16 of 60 · 25 min
Classes and objects
Explanation
Why classes?
So far you have used separate variables and static methods. Real programs model things: an account has an owner and a balance and can deposit and withdraw; a product has a name, a price and stock. A class groups the data of a thing with the code that works on that data. This style is object-oriented programming (OOP).
public class BankAccount {
String owner; // fields: the data each object has
double balance;
void deposit(double amount) { // instance method: works on THIS object's fields
balance += amount;
}
void show() {
System.out.println(owner + " has Rs " + balance);
}
}Creating objects
BankAccount a = new BankAccount(); // new builds an object on the heap
a.owner = "Asha";
a.deposit(5000);
BankAccount b = new BankAccount(); // a second, independent object
b.owner = "Ravi";
b.deposit(1200);
a.show(); // Asha has Rs 5000.0
b.show(); // Ravi has Rs 1200.0Each object has its own copy of the fields. a.deposit changes only a's balance. Fields get default values (0, 0.0, false, null) if you do not set them.
References and the heap
Objects live in a memory area called the heap. A variable like a does not contain the object; it holds a reference (like an address) to it. Assigning BankAccount c = a; copies the reference, so c and a refer to the same account. A reference that points to nothing is null; calling a method on null throws NullPointerException.
BankAccount c = a; // same object as a
c.deposit(100);
a.show(); // Asha has Rs 5100.0
BankAccount nobody = null;
// nobody.show(); // NullPointerExceptionInstance members versus static members
Fields and methods without static belong to each object (instance members): every account has its own balance. Members marked static belong to the class as a whole (topic 4). Inside an instance method you can use fields directly; the full form is this.balance, where this means "the object this method was called on".
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Classes and objects · 1/6
In this lesson you will create your own classes and objects.
Prefer a video by a teacher? Find free videos on “java classes and objects tutorial for beginners oop” on YouTube ↗
In real life: Products in an online store
An e-commerce catalogue has thousands of products. Each is an object of one Product class, with its own name, price and stock, and a method to check availability. The code that lists products just calls methods on each object.
class Product {
String name;
double price;
int stock;
boolean isAvailable(int qty) { return stock >= qty; }
}
// Product p = new Product(); p.name = "Steel bottle"; p.price = 349; p.stock = 12;
// p.isAvailable(2) → truePractice (0/3 done)
What does this print? class Counter { int n; void inc() { n++; } } … Counter a = new Counter(); Counter b = a; Counter c = new Counter(); a.inc(); b.inc(); c.inc(); System.out.println(a.n + " " + c.n);
The same class idea in JavaScript, which runs here: write a class BankAccount with a constructor(owner) that sets balance to 0, deposit(amount) and withdraw(amount) (returns false and changes nothing if amount > balance), and a show() that returns "<owner>: Rs <balance>".
Write a Java class Student with fields name, roll and marks (int[]), and methods total() and average(). In main, create three Student objects and print each one's average.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Constructors and thisClasses and objects · same module
- Encapsulation: private fields, getters and settersClasses and objects · same module
- static members and finalClasses and objects · same module
- Classes and objects: data plus behaviourC++ Programming (modern C++ and DSA) · Classes, constructors and RAII
- Classes, objects and constructorsC# and .NET · Classes and objects
- Classes and objectsPython Programming · Object-oriented programming
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What does the new keyword do?
Answer: Creates an object and returns a reference to it
new allocates and initialises a new object.
Two objects of the same class…
Answer: Each have their own copies of instance fields
Instance fields belong to each object.
What is the default value of an uninitialised String field?
Answer: null
Object fields default to null (unlike local variables, which have no default).
Inside an instance method, what does this refer to?
Answer: The object the method was called on
this is the current object.
A static member variable is…Related
Answer: shared by the whole class, one copy in total
Static members belong to the class, not to individual objects.
Without overriding ToString, what does printing an object of class City show?Related
Answer: Its class name (like City)
The default ToString returns the type's full name.
What is the difference between a class and an object?Related
Answer: A class is the blueprint; an object is one thing made from it
One class can make many objects, each with its own data.
From Classes and objects
What makes a class field private?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 4 more topics in “Classes and objects” before its exam: Constructors and this, Encapsulation: private fields, getters and setters, static members and final, toString, equals, hashCode and records.
- Module 4 exam: Classes and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Inheritance, polymorphism and interfaces. 60 topics left in the course before the final exam.