Java Class Example

Use classes. Understand how classes store data and provide methods.
Classes. Programs are built of concepts. And classes, building blocks, contain the data and internal logic. They are conceptual units. Classes compose programs.
An example. This example uses a custom class (Box). This class is stored in a file called In Box, we have a constructor, two fields and a method.

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, 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, 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
This. We use the "this" keyword to access the current instance from a method. We can access other methods with this, or the current instance itself.This
Extends, super. With the extends keyword we implement inheritance. A class that inherits from another extends it. We can access the parent class instance with super.ExtendsSuper
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.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to