Methods
Teach the blueprint a trick.
1class Dog {
2 String name;
3
4 void bark() {
5 System.out.println(name + " says woof!");
6 }
7}
8
9public static void main(String[] args) {
10 Dog rex = new Dog();
11 rex.name = "Rex";
12 rex.bark();
13}
$ javac Main.java
$ java Main
Rex says woof!
Every line, explained
class Dog {- class Dog { ... } defines a class: a blueprint describing what every Dog has and can do. A blueprint on its own does nothing; it is a plan, waiting to be built from.
String name;- A variable declared inside a class is called a field. Every Dog built from this blueprint gets its OWN copy: its own little name box.
void bark() {- A method inside a class is something every Dog can DO. Fields are what an object has; methods are what it can do.
System.out.println(name + " says woof!");- Inside a method, you can use the fields directly: name here means "MY name, the name of whichever dog is barking".
}- This } closes the method.
}- This } closes the class.
public static void main(String[] args) {- The main method: where the program starts, exactly as in Intro to Java.
Dog rex = new Dog();- new Dog() builds a real object from the blueprint. The blueprint is the plan; the object is an actual dog. We store it in a variable of type Dog.
rex.name = "Rex";- The dot reaches inside an object: rex.name means "the name field of the object stored in rex".
rex.bark();- The dot calls a method too: rex.bark() means "rex, do your bark trick!". Because it is rex barking, the method prints rex's name.
}- This } closes the main method.