Classes and objects
Java is an object-oriented language: programs are built from objects that bundle data (fields) with behaviour (methods). A class is the blueprint, and each object made from it is an instance.
Your first class
class Dog {
String name; // fields: each Dog has its own
String breed;
int tricks = 0;
Dog(String name, String breed) { // constructor: runs when you write new Dog(...)
this.name = name; // this.name = the field; name = the parameter
this.breed = breed;
}
void learnTrick() { // an instance method
tricks++;
}
String describe() {
return name + " the " + breed + " knows " + tricks + " tricks";
}
}
public class Main {
public static void main(String[] args) {
Dog rex = new Dog("Rex", "beagle");
Dog bella = new Dog("Bella", "husky");
rex.learnTrick();
rex.learnTrick();
System.out.println(rex.describe());
System.out.println(bella.describe());
}
}Rex the beagle knows 2 tricks Bella the husky knows 0 tricks
new Dog(...)creates an object and runs the constructor.thisrefers to the current object.- Every object has its own copy of the fields: Rex's tricks aren't Bella's.
A file can contain several classes, but only one
publicclass, which must match the file name. In real projects, each class usually gets its own file.
Encapsulation: private fields
If anyone can change any field, objects can end up in invalid states (like a negative balance). Encapsulation hides fields with private and exposes safe methods instead:
class BankAccount {
private final String owner; // final: set once in the constructor, never changed
private double balance;
BankAccount(String owner, double openingBalance) {
if (openingBalance < 0) throw new IllegalArgumentException("Opening balance can't be negative");
this.owner = owner;
this.balance = openingBalance;
}
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Deposit must be positive");
balance += amount;
}
public boolean withdraw(double amount) {
if (amount > balance) return false; // refuse instead of going negative
balance -= amount;
return true;
}
public double getBalance() { return balance; } // a "getter"
public String getOwner() { return owner; }
}
public class Main {
public static void main(String[] args) {
BankAccount acct = new BankAccount("Asha", 100);
acct.deposit(50);
System.out.println(acct.withdraw(30));
System.out.println(acct.withdraw(500));
System.out.println(acct.getOwner() + " has " + acct.getBalance());
}
}true false Asha has 120.0
Trying acct.balance = 1_000_000; from Main won't compile: balance has private access in BankAccount. The class controls every change to its data.
Access modifiers
| Modifier | Visible from |
|---|---|
private |
Only inside the same class |
| (none) | The same package |
protected |
The same package and subclasses |
public |
Everywhere |
Rule of thumb: fields private, methods public only if other classes need them.
static: belonging to the class
static fields and methods belong to the class itself, not to any one object. That's why main is static: Java calls it before any object exists.
class User {
private static int count = 0; // shared by all users
private final int id;
private final String name;
User(String name) {
count++;
this.id = count;
this.name = name;
}
static int getCount() { return count; }
@Override
public String toString() { // used when printing the object
return "User#" + id + "(" + name + ")";
}
}
public class Main {
public static void main(String[] args) {
User a = new User("Asha");
User b = new User("Rahul");
System.out.println(a + " " + b);
System.out.println("Users created: " + User.getCount());
System.out.println(Math.max(3, 9)); // Math's methods are static too
}
}User#1(Asha) User#2(Rahul) Users created: 2 9
toString, equals and hashCode
Every class inherits these from Object. The defaults are rarely what you want:
class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
}
class BetterPoint {
final int x, y;
BetterPoint(int x, int y) { this.x = x; this.y = y; }
@Override
public String toString() { return "(" + x + ", " + y + ")"; }
@Override
public boolean equals(Object o) {
return o instanceof BetterPoint p && p.x == x && p.y == y;
}
@Override
public int hashCode() { return java.util.Objects.hash(x, y); }
}
public class Main {
public static void main(String[] args) {
System.out.println(new Point(1, 2).equals(new Point(1, 2)));
System.out.println(new BetterPoint(1, 2).equals(new BetterPoint(1, 2)));
System.out.println(new BetterPoint(1, 2));
}
}false true (1, 2)
The default equals checks whether two references point to the same object. If you override equals, always override hashCode too, or objects will misbehave in HashMap and HashSet. (In the modern Java lesson you'll see records, which generate all of this for you.)
Constructors: overloading and chaining
class Pizza {
private final String size;
private final String[] toppings;
Pizza(String size, String... toppings) {
this.size = size;
this.toppings = toppings;
}
Pizza() {
this("medium", "cheese"); // call the other constructor
}
@Override
public String toString() {
return size + " pizza with " + String.join(", ", toppings);
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Pizza());
System.out.println(new Pizza("large", "mushroom", "olives", "basil"));
}
}medium pizza with cheese large pizza with mushroom, olives, basil
References and null
Variables of class types hold references (like addresses) to objects. Two variables can refer to the same object, and a reference can be null (pointing at nothing):
class Counter {
int value;
}
public class Main {
public static void main(String[] args) {
Counter a = new Counter();
Counter b = a; // same object, two names
b.value = 10;
System.out.println(a.value);
Counter c = null;
System.out.println(c.value);
}
}10 Exception in thread "main" java.lang.NullPointerException: Cannot read field "value" because "<local3>" is null at Main.main(Main.java:13)
NullPointerException is the most common Java crash. Check for null, avoid returning it where you can (return an empty list or Optional instead), and initialise fields in constructors.
Practice
- Write a
Rectangleclass with privatewidthandheight, a constructor that rejects non-positive values, andarea(),perimeter()andtoString()methods. - Write a
Productclass with a name and price, and aCartclass that holds an array of up to 10 products, withadd(Product)andtotal()methods. - Give
ProductanequalsandhashCodebased on its name.
1.What does a constructor do?
2.Why make fields private?
3.What does a static field belong to?