Blueprints and real things
Java is an object-oriented language. That means programs are built from objects that hold data and can do things.
Think of it like this: A class is like the blueprint of a car: it says every car has a colour and a speed, and can drive. An object is one real car built from that blueprint – a red one, a blue one. One blueprint, many cars.
Writing a class
class Dog {
String name;
int age;
void bark() {
System.out.println(name + " says Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.name = "Bruno";
d1.age = 3;
Dog d2 = new Dog();
d2.name = "Tiger";
d2.age = 5;
d1.bark();
d2.bark();
System.out.println(d2.name + " is " + d2.age);
}
}Output
Bruno says Woof! Tiger says Woof! Tiger is 5
| Word | Meaning | Here |
|---|---|---|
| class | the blueprint | Dog |
| field | a piece of data every object has | name, age |
| method | something every object can do | bark() |
| object | one real thing made from the class | d1, d2 |
new | build a new object | new Dog() |
Each object has its own copy of the fields. Changing d1.name doesn't touch d2.
Tip: In this course everything goes in one file, so other classes are written without
public. In real projects, each public class usually gets its own file, likeDog.java.