Classes and Objects

Programming Languages · Java Objects · 15 min

Design your own types with classes, then create objects from them.

A class is a blueprint

A class is a blueprint, and an object is a thing built from it. The class Dog says every dog has a name and an age (its fields). new Dog() builds one actual dog.

Use a dot to reach an object's fields.

Dog d = new Dog();
d.name = "Fido";
  • In main, create a Dog called myDog with new Dog().

  • Set myDog.name to "Rex", then print myDog.name.

Constructors

A constructor sets up a new object. It has the same name as the class and no return type. this.name means "this object's own name field", which tells it apart from the parameter name.

Cat(String name) {
    this.name = name;
}
Cat c = new Cat("Tom");
  • Give Dog a constructor that takes String name, int age and stores both in the fields.

  • In main, create new Dog("Rex", 3) and print its age.

Methods on objects

A class can have methods too. They don't need static, because they belong to each object and can use its fields. Call them with a dot.

void sit() {
    System.out.println(name + " sits");
}
rex.sit(); // Rex sits
  • Add a method void bark() to Dog that prints name + " says Woof!".

  • In main, create a dog named "Rex" and call its bark().

Many objects, one class

One blueprint can build as many objects as you like. Each object gets its own copy of the fields, so changing one dog never changes another.

Dog a = new Dog("Rex");
Dog b = new Dog("Bella");
  • Create two dogs: "Rex" and "Bella".

  • Call bark() on Rex, then on Bella.

Printing objects: toString

Run the starter: printing a dog shows something like Dog@5ca881b5. Java doesn't know how to describe your object yet.

Add a toString() method that returns a String, and println will use it automatically.

public String toString() {
    return "Cat called " + name;
}
  • Add public String toString() to Dog so that printing rex shows Rex (3).

Put it together: a bank account

Design a BankAccount class. It knows its owner and balance, lets you deposit money, and describes itself with toString(). A new account starts with a balance of 0.

  • Give BankAccount the fields String owner and double balance, and a constructor that takes the owner.

  • Add void deposit(double amount) that adds amount to balance.

  • Add a toString() that returns owner + ": " + balance. In main, make an account for "Ada", deposit 100 and 50, and print it.

More in Java Objects

Previous: Methods · Next: ArrayList and HashMap