Home
Java
class Example
Updated 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 21, 2024 (new example).
Home
Changes
© 2007-2025 Sam Allen