Java from zero: a class holds the data and the method
A class groups fields and a method. Item stores a drink and a price in cents. label prints latte $4.50.
Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.
A drink is a name and a price. A class is the object that holds both, plus the method that uses them. You make one latte with new. You call the method on that latte.
A class is data and the methods that see it#
A class describes a layout and the methods that operate on it. new Item("latte", 450) allocates an object and runs the constructor, which copies the two arguments into the fields. this is that object. label reads the fields through this and returns a new string. The int stays an int inside the object. The string latte $4.50 exists only as the return value. Nothing in the method changes the stored cents.
- nameStringlatte
- centsint450
- label()Stringlatte $4.50
public class Main {
static class Item {
String name;
int cents;
Item(String name, int cents) {
this.name = name;
this.cents = cents;
}
String label() {
return String.format("%s $%d.%02d", name, cents / 100, cents % 100);
}
}
public static void main(String[] args) {
Item latte = new Item("latte", 450);
System.out.println(latte.label());
}
}
latte $4.50
new calls the constructor#
Item has two fields and one constructor. The constructor's job is to fill the fields. this.name = name stores the argument in the field. The two names are different: the argument is the parameter, and this.name is the field on the object. new Item("latte", 450) runs that constructor and gives you the object.
label reads the fields and returns the text. latte.label() is the call. The method does not take the name and the price as arguments, because they are already on latte.
Cents stay a whole number#
450 is the price in cents. The field type is int, so a fraction cannot land there by accident. label shows that as $4.50. The object stores 450. The next lesson is the tip about a variable that does not point at an object yet.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.