Java tutorialLesson 10 of 18 · tap to see all lessons
Java tutorial · Beginner
Java Classes and Objects: Fields, Methods, and Object References
Declare a Java class, create objects with new, use fields and instance methods, understand object references and null, and make many objects from one class.
- Qyubie Learn Editorial Team
- Published
- 8 min read
Includes 2 quick checks you can do right here.
In the last lesson you saw why objects help. Now you'll build them. A class describes what every object of that kind has (its fields) and does (its methods). The new keyword then creates objects from it, as many as you need.
By the end of this lesson you will be able to:
- declare a class with fields and methods,
- create objects with
newand use them with the dot operator, - explain instance variables and their default values, and
- explain what an object reference is, including
nulland two variables pointing to the same object.
Declaring a class
A class has a name (PascalCase), fields for its data, and methods for its behavior:
class BankAccount {
// fields (attributes)
String owner;
double balance;
// methods (behaviors)
void deposit(double amount) {
balance += amount;
}
void showBalance() {
System.out.printf("%s: %.2f%n", owner, balance);
}
}Two things are different from the methods in lesson 8:
- These methods are not
static. They belong to each object, so they work on that object's ownbalance. - Inside a method,
balanceandownermean this object's fields.
UML class diagrams, which you'll draw in lab, show the same class as a box with three parts:
+---------------------------+
| BankAccount |
+---------------------------+
| owner : String |
| balance : double |
+---------------------------+
| deposit(amount : double) |
| showBalance() |
+---------------------------+Creating objects with new
new BankAccount() creates an object (an instance) and gives back a reference to it, which you store in a variable of the class type. Use the dot operator to reach its fields and methods.
class BankAccount {
String owner;
double balance;
void deposit(double amount) {
balance += amount;
}
void showBalance() {
System.out.printf("%s: %.2f%n", owner, balance);
}
}
public class Bank {
public static void main(String[] args) {
BankAccount acc = new BankAccount(); // create an object
acc.owner = "Ana"; // set a field
acc.deposit(500); // call a method
acc.deposit(250.50);
acc.showBalance();
}
}Output:
Ana: 750.50Several classes can share one file, as here, but only one may be public, and the file is named after it (Bank.java). In bigger projects, put each class in its own file.
Instance variables and default values
Fields declared in a class (not inside a method) are instance variables: every object gets its own copy. Unlike local variables, fields get default values if you don't set them:
| Field type | Default |
|---|---|
int, long, double, … | 0 or 0.0 |
boolean | false |
char | '\u0000' (the null character) |
any object type (String, arrays, …) | null |
class Item {
String name;
int quantity;
boolean available;
}
public class Defaults {
public static void main(String[] args) {
Item it = new Item();
System.out.println(it.name);
System.out.println(it.quantity);
System.out.println(it.available);
}
}Output:
null
0
falseMany objects from one class
Each object has its own field values. Changing one doesn't touch the others:
class Student {
String name;
int score;
String remark() {
return score >= 75 ? "Passed" : "Failed";
}
}
public class Roster {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Ana";
s1.score = 88;
Student s2 = new Student();
s2.name = "Ben";
s2.score = 70;
Student[] all = {s1, s2}; // an array of objects
for (Student s : all) {
System.out.println(s.name + " - " + s.remark());
}
}
}Output:
Ana - Passed
Ben - FailedAn array of objects is how you'll keep a list of records until you meet ArrayList in lesson 18.
Quick check
Object references
A variable of a class type doesn't hold the object itself. It holds a reference, which is like an address that leads to the object. This matters when you copy the variable:
class Box {
int size;
}
public class Refs {
public static void main(String[] args) {
Box a = new Box();
a.size = 5;
Box b = a; // copies the reference, not the object
b.size = 99;
System.out.println(a.size);
System.out.println(a == b);
Box c = new Box();
c.size = 99;
System.out.println(a == c);
}
}Output:
99
true
falseBox b = a;doesn't create a second box. Nowaandbboth refer to the same object, so changing it throughbis visible througha.==on objects asks "same object?", not "same contents?".aandchold equal values but are different objects, soa == cisfalse. (That's why Strings need.equals().)
null means a reference that points to no object. Calling a method or reading a field through null causes a NullPointerException:
Student s = null;
System.out.println(s.name); // NullPointerExceptionQuick check
Common mistakes
- Forgetting
new:Student s; s.name = "Ana";won't compile, becauseswas never given an object. - Calling an instance method from
static mainwithout an object:deposit(100);alone fails. Call it on an object:acc.deposit(100);. - Expecting
b = ato copy the object. It copies the reference. - Comparing objects with
==when you mean "same contents". - Making two classes
publicin one file.
Summary
- A class declares fields (data) and methods (behavior);
newcreates objects from it. - Use the dot operator:
obj.field,obj.method(). - Each object has its own copy of the instance variables, and fields get default values.
- Variables of class types hold references. Assigning copies the reference,
==compares references, andnullmeans no object.
Next lesson: constructors: setting up an object's fields the moment it's created.