Skip to content

Module 5 · Classes and Objects — topic 1 of 4

Classes and Objects

Defining a class with fields and methods, creating objects with new, references and null, toString, and how objects are shared between variables.

Beginner 16 min read·Lesson 16 of 39 in Java Programming

Learning objectives

  • Define a class with fields and instance methods
  • Create objects and call their methods
  • Explain references, null and object identity

Definition

A class is a blueprint that defines the state (fields) and behaviour (methods) of a kind of object. An object is an instance of a class created at run time with new; variables of a class type hold references to objects.

Introduction

So far your programs have used built-in types such as int, String and arrays. Object-oriented programming lets you define your own types that match the problem: a Student, a BankAccount, a Product. Each type bundles the data it needs with the operations that make sense for it.

A class is written once; you can then create as many objects of it as you need. Each object has its own copy of the fields, so two BankAccount objects have two separate balances.

Why it matters

Classes are how real Java applications are organised: every framework, library and project in this course is built from them.

Bundling data with behaviour keeps related code together and makes large programs manageable.

Detailed explanation

Fields (instance variables) are declared inside the class but outside any method. Every object gets its own copy, initialised to default values (0, false, null) unless you assign them.

Instance methods are declared without static. They run *on* an object and can read and change that object's fields: account.deposit(500).

Creating objects. new BankAccount() allocates an object on the heap, initialises its fields and returns a reference. BankAccount acc = new BankAccount(); stores that reference in a variable.

References. Assigning one variable to another (b = a) copies the reference, so both refer to the same object. == compares references; two distinct objects with the same field values are not ==.

null. A reference variable can hold null, meaning 'no object'. Calling a method through a null reference throws NullPointerException — the most common run-time error in Java. Java 14+ explains which variable was null in the message.

toString. Every class inherits toString() from Object. Overriding it to return a readable description makes printing and debugging much easier; println(obj) and "" + obj call it automatically.

Objects that are no longer referenced are reclaimed by the garbage collector; there is no delete in Java.

Syntax

Java
class Student {
String name; // fields
int marks;
boolean passed() { // instance method
return marks >= 40;
}
@Override
public String toString() { return name + " (" + marks + ")"; }
}
Student s = new Student(); // create an object
s.name = "Asha";
s.marks = 82;
System.out.println(s + " passed: " + s.passed());
  • Class names use PascalCase; field and method names use camelCase.
  • Only one public top-level class per file; other classes in the file are package-private.
  • Fields are usually private — see Encapsulation.

Code examples

A first class

Java
public class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.width = 4;
r1.height = 2.5;
Rectangle r2 = new Rectangle();
r2.width = 3;
r2.height = 3;
System.out.println(r1 + " area " + r1.area());
System.out.println(r2 + " area " + r2.area() + " square? " + r2.isSquare());
}
}
class Rectangle {
double width;
double height;
double area() { return width * height; }
boolean isSquare() { return width == height; }
@Override
public String toString() { return "Rectangle[" + width + " x " + height + "]"; }
}
Output
Rectangle[4.0 x 2.5] area 10.0
Rectangle[3.0 x 3.0] area 9.0 square? true

References and identity

Java
public class Main {
public static void main(String[] args) {
Counter a = new Counter();
Counter b = a; // same object
Counter c = new Counter(); // a different object
a.increment();
b.increment();
System.out.println(a.count + " " + b.count + " " + c.count);
System.out.println((a == b) + " " + (a == c));
Counter none = null;
try {
none.increment();
} catch (NullPointerException e) {
System.out.println("NullPointerException: no object to increment");
}
}
}
class Counter {
int count;
void increment() { count++; }
}
Output
2 2 0
true false
NullPointerException: no object to increment

More examples

Objects working together

Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Course course = new Course();
course.title = "Java Programming";
String[] names = {"Asha", "Ravi", "Meera"};
int[] marks = {82, 35, 91};
for (int i = 0; i < names.length; i++) {
Student s = new Student();
s.name = names[i];
s.marks = marks[i];
course.enrol(s);
}
System.out.println(course);
System.out.println("Average: " + course.average());
System.out.println("Top: " + course.top());
System.out.println("Passed: " + course.countPassed() + "/" + course.students.size());
}
}
class Student {
String name;
int marks;
boolean passed() { return marks >= 40; }
@Override public String toString() { return name + "(" + marks + ")"; }
}
class Course {
String title;
List<Student> students = new ArrayList<>();
void enrol(Student s) { students.add(s); }
double average() {
int sum = 0;
for (Student s : students) sum += s.marks;
return students.isEmpty() ? 0 : (double) sum / students.size();
}
Student top() {
Student best = null;
for (Student s : students)
if (best == null || s.marks > best.marks) best = s;
return best;
}
int countPassed() {
int n = 0;
for (Student s : students) if (s.passed()) n++;
return n;
}
@Override public String toString() { return title + " " + students; }
}
Output
Java Programming [Asha(82), Ravi(35), Meera(91)]
Average: 69.33333333333333
Top: Meera(91)
Passed: 2/3

Step-by-step explanation

  • main creates one Course and three Student objects, setting each student's fields.
  • course.enrol(s) passes a reference to the student; the course's list now refers to the same object.
  • Printing the course calls Course.toString, which prints the list, which in turn calls each Student.toString.
  • average, top and countPassed are instance methods that work with the course's own students field.
  • top starts with best = null and the condition best == null || handles the first student safely.

Expected output

Running “Objects working together” prints exactly:

TextOutput
Java Programming [Asha(82), Ravi(35), Meera(91)]
Average: 69.33333333333333
Top: Meera(91)
Passed: 2/3

Practical applications

  • Domain models such as Order, Customer and Invoice in business software
  • Game entities such as Player, Enemy and Bullet
  • Data transfer objects that carry data between layers of an application

Best practices

  • Give every class a single clear responsibility.
  • Override toString in every domain class to make debugging easy.
  • Check for null (or avoid returning null) before calling methods on references.

Common mistakes

Using an object before creating it

Avoid

Student s;
s.name = "Asha"; // compile error: not initialised

Prefer

Student s = new Student();
s.name = "Asha";

A declaration creates only a reference variable; new creates the object.

Comparing objects with ==

Avoid

if (p1 == p2) ... // same object?

Prefer

if (p1.equals(p2)) ... // equal contents (equals must be overridden)

== checks identity. Content comparison needs equals, which you'll learn to override in module 7.

Important notes

  • Several classes may live in one file, but only one may be public and it must match the file name.
  • An object's fields live on the heap; local reference variables live on the stack and point to them.

Key takeaways

  • A class defines fields and methods; objects are created from it with new.
  • Variables of class type hold references; assignment shares the object.
  • Calling a method on null throws NullPointerException.

Try it yourself

  1. 1
    Write a Book class with title, author and pages, and a method isLong() for books over 300 pages.
  2. 2
    Create two variables that refer to the same Book, change the title through one, and print it through the other.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat does `Student s = new Student();` do?
  • BeginnerWhat is printed?
  • BeginnerWhat happens? `Student s = null; s.getName();`
Practise this topic