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 aDogcalledmyDogwithnew Dog().Set
myDog.nameto"Rex", then printmyDog.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
Doga constructor that takesString name, int ageand stores both in the fields.In
main, createnew Dog("Rex", 3)and print itsage.
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()toDogthat printsname + " says Woof!".In
main, create a dog named"Rex"and call itsbark().
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()toDogso that printingrexshowsRex (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
BankAccountthe fieldsString owneranddouble balance, and a constructor that takes the owner.Add
void deposit(double amount)that addsamounttobalance.Add a
toString()that returnsowner + ": " + balance. Inmain, make an account for"Ada", deposit100and50, and print it.
More in Java Objects
Previous: Methods · Next: ArrayList and HashMap