C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Box: In the main method, we create two new instances of the Box class. These exist separately in memory.
Area: We call the area method on each Box instance, box1 and box2. This multiplies the two int fields and returns a number.
Tip: A class has a means of creation (the constructor). And it provides behavior, in its area() method. It has data (width and height).
Java program that instantiates class, Program.java
public class Program {
public static void main(String[] args) {
// Create box.
Box box1 = new Box(2, 3);
int area1 = box1.area();
// Create another box.
Box box2 = new Box(1, 5);
int area2 = box2.area();
// Display areas.
System.out.println(area1);
System.out.println(area2);
}
}
Class definition, Box.java
public class Box {
int width;
int height;
public Box(int width, int height) {
// Store arguments as fields.
this.width = width;
this.height = height;
}
public int area() {
// Return area.
return this.width * this.height;
}
}
Output
6
5