Home
Java
class Example
This page was last reviewed on Jan 21, 2024.
Dot Net Perls
Classes. Programs are built of concepts. And classes, building blocks, contain the data and internal logic. They are conceptual units. Classes compose programs.
Useful Java keywords. In addition to the class keyword, we can use "extends" and "super" in programs that use classes. And "this" references a class instance.
extends
super
this
Class example. This example uses a custom class (Box). This class is stored in a file called Box.java. In Box, we have a constructor, two fields and a method.
Constructor
Start In the main method, we create two new instances of the Box class. These exist separately in memory.
Next We call the area method on each Box instance, box1 and box2. This multiplies the two int fields and returns a number.
Method
Tip A class has a means of creation (the constructor). And it provides behavior, in its area() method. It has data (width and height).
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); } }
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; } }
6 5
Record. For simpler classes, with just a few fields and no custom methods, a record can be a good choice. It reduces the number of lines of code needed to store data together.
record
public class Program { // Example record. record Item(String name, int color) {} public static void main(String[] args) { Item item = new Item("box", 4); System.out.println(item); } }
Item[name=box, color=4]
Some concepts. When using classes in Java we must combine many concepts. We need constructors, and often we use interfaces and abstract classes.
abstract
interface
Objects
Classes are the core unit around which we develop programs. They combine data, in the form of fields, and behavior, in methods. And with constructors we instantiate them.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 21, 2024 (new example).
Home
Changes
© 2007-2024 Sam Allen.