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.
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
- 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
Rectangle[4.0 x 2.5] area 10.0 Rectangle[3.0 x 3.0] area 9.0 square? true
References and identity
2 2 0 true false NullPointerException: no object to increment
More examples
Objects working together
Java Programming [Asha(82), Ravi(35), Meera(91)] Average: 69.33333333333333 Top: Meera(91) Passed: 2/3
Step-by-step explanation
maincreates oneCourseand threeStudentobjects, 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 eachStudent.toString. average,topandcountPassedare instance methods that work with the course's ownstudentsfield.topstarts withbest = nulland the conditionbest == null ||handles the first student safely.
Expected output
Running “Objects working together” prints exactly:
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
Prefer
A declaration creates only a reference variable; new creates the object.
Comparing objects with ==
Avoid
Prefer
== 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
- 1Write a
Bookclass with title, author and pages, and a methodisLong()for books over 300 pages. - 2Create 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();`