Java Tutorial · Object-Oriented Java · Lesson 19 of 37
Java Classes and Objects
Define classes with fields and methods, create objects and use constructors.
Classes and objects
A class is a template; an object is an instance of it with its own field values. Create objects with new; a constructor initialises them. this refers to the current object:
public class Main {
public static void main(String[] args) {
Car a = new Car("Toyota", 2020);
Car b = new Car("Volvo");
a.drive(150);
System.out.println(a.describe());
System.out.println(b.describe());
}
}
class Car {
String brand;
int year;
int km;
Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
Car(String brand) {
this(brand, 2026); // call the other constructor
}
void drive(int distance) {
km += distance;
}
String describe() {
return brand + " (" + year + "), " + km + " km";
}
}
Output
Toyota (2020), 150 km Volvo (2026), 0 km
Run this on your computer — see “Get Started” for setup.
toString, equals and hashCode
Override toString() for readable output. If two objects should be considered equal by their contents, override both equals() and hashCode() — otherwise HashSet and HashMap won't work correctly. (Or use a record, which generates them for you.)
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
public class Main {
public static void main(String[] args) {
Book a = new Book("Dune", "Herbert");
Book b = new Book("Dune", "Herbert");
System.out.println(a);
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(new HashSet<>(List.of(a, b)).size());
}
}
class Book {
private final String title;
private final String author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public String toString() {
return title + " by " + author;
}
@Override
public boolean equals(Object o) {
return o instanceof Book other && title.equals(other.title) && author.equals(other.author);
}
@Override
public int hashCode() {
return Objects.hash(title, author);
}
}
Output
Dune by Herbert false true 1
Run this on your computer — see “Get Started” for setup.
Test yourself
Which keyword creates a new object?
createnewmakethis
Show answer
Answer: new
Practice next
- equals() and hashCode() Done Right · coding problem