Java Class Methods
Methods give objects their behaviour. In the Methods section you wrote static methods that live on the class. Now you'll write instance methods — methods without static that run on a particular object and can read and change that object's fields.
Instance methods
class Lamp {
boolean on;
int brightness = 50;
void toggle() {
on = !on;
}
void dim(int amount) {
brightness = Math.max(0, brightness - amount);
}
String status() {
return on ? "ON at " + brightness + "%" : "OFF";
}
}
class Main {
public static void main(String[] args) {
Lamp desk = new Lamp();
Lamp ceiling = new Lamp();
desk.toggle();
desk.dim(20);
System.out.println("desk: " + desk.status());
System.out.println("ceiling: " + ceiling.status());
}
}desk: ON at 30%
ceiling: OFF
Inside toggle, the name on refers to the field of whichever lamp the method was called on. desk.toggle() changes the desk lamp; the ceiling lamp is untouched.
Static vs. instance methods
static method |
instance method | |
|---|---|---|
| Called as | ClassName.method() |
object.method() |
| Needs an object | no | yes |
| Can use instance fields | no | yes |
| Can use static fields | yes | yes |
| Typical use | utilities, factories, main |
behaviour of one object |
class Temperature {
double celsius;
// instance method: works on this object's data
double toFahrenheit() {
return celsius * 9 / 5 + 32;
}
// static method: needs no object
static Temperature fromFahrenheit(double f) {
Temperature t = new Temperature();
t.celsius = (f - 32) * 5 / 9;
return t;
}
}
class Main {
public static void main(String[] args) {
Temperature room = new Temperature();
room.celsius = 21;
System.out.println(room.toFahrenheit());
Temperature oven = Temperature.fromFahrenheit(392);
System.out.println(oven.celsius);
}
}69.8
200.0
A static method can't use an instance field directly, because there's no object to take it from. This is why main can't just call an instance method without first creating an object:
class Main {
void hello() { System.out.println("hi"); }
public static void main(String[] args) {
hello(); // error: non-static method hello() cannot be referenced from a static context
new Main().hello(); // works: call it on an object
}
}Methods that use other methods
Methods of the same class can call each other directly:
class ShoppingCart {
double subtotal;
int itemCount;
void add(double price, int qty) {
subtotal += price * qty;
itemCount += qty;
}
double discount() {
return itemCount >= 5 ? subtotal * 0.1 : 0;
}
double total() {
return subtotal - discount();
}
void printReceipt() {
System.out.printf("Items: %d%n", itemCount);
System.out.printf("Subtotal: %.2f%n", subtotal);
System.out.printf("Discount: %.2f%n", discount());
System.out.printf("Total: %.2f%n", total());
}
}
class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.add(3.50, 2);
cart.add(12.00, 1);
cart.add(1.25, 4);
cart.printReceipt();
}
}Items: 7
Subtotal: 24.00
Discount: 2.40
Total: 21.60
toString: describing an object
Every class inherits a toString() method that println calls automatically. The inherited version prints something like Book@1b6d3586, which isn't helpful. Write your own version to control the text:
class Book {
String title;
int year;
@Override
public String toString() {
return title + " (" + year + ")";
}
}
class Main {
public static void main(String[] args) {
Book b = new Book();
b.title = "Neuromancer";
b.year = 1984;
System.out.println(b);
System.out.println("Favourite: " + b);
}
}Neuromancer (1984)
Favourite: Neuromancer (1984)
@Override tells the compiler you intend to replace an inherited method; it will warn you if the signature is wrong. toString must be public — you'll learn why in the Inheritance chapter.
Test yourself
Which method can access an instance field directly?
- Any static method
- Only main
- An instance (non-static) method of the same class
- None
How do you call an instance method start() from main?
- start();
- Main.start();
- Create an object and call obj.start();
- static start();
Which method does System.out.println(obj) use to get the text?
- obj.print()
- obj.toString()
- obj.getText()
- obj.name()