Home
Map
Class ExampleUnderstand how classes improve programs by storing data and providing methods.
Java
This page was last reviewed on Dec 7, 2021.
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.
Detail In the main method, we create two new instances of the Box class. These exist separately in memory.
Detail We call the area method on each Box instance, box1 and box2. This multiplies the two int fields and returns a number.
Methods
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
Abstract. With this keyword we create a class that can only be used as a template for a more derived class. An abstract class cannot be created directly.
Abstract
Constructors. These are used to create new instances of classes. With constructors, we restrict how classes are instantiated. And we validate and initialize data in them.
Constructors
Objects. The object class is a superclass: every instance in Java has Object as a parent. And in the Objects class, we find utility methods for handling, validating, and comparing objects.
Objects
Interface. This is a cross-class abstraction. We isolate features that are used in many classes. Then with an interface reference, we can use those classes in a unified way.
Interfaces
A summary. 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.
C#VB.NETPythonGolangJavaSwiftRust
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 Dec 7, 2021 (edit).
Home
Changes
© 2007-2023 Sam Allen.