Home Java Introduction to Classes in Java

Introduction to Classes in Java

Java is the most famous object-oriented language used by programmers today. To get an in-depth narrative of how java works, we need to have a deep understanding of classes and objects. Let’s dive into the world of objects and classes and have a first look at how they operate.

Objects and Classes

If we look at a car, we can see it consists of many components like wheels, windows, accelerator pedal, brake pedal, and so on. There are many components under the hood that we do not see, like engine, radiator, etc. When we talk about a car, it is not just one object but a collection of objects working together.

The same notion applies to computer programming, but the object is not a physical device. In java, an object can do 2 things:

  • It can store data
  • It can perform operations

So objects play an important role in an object-oriented language. For example, if you need to read input from the console, you need a scanner object. The question is how do we use these objects? Well, they don’t just magically appear in a program; we need to create an object in memory, and before creating an object, we need a class.

A class describes a particular object, so we can say that a class is a blueprint of an object. Let’s begin with a demo of an actual code that shows Java classes and objects.

import java.util.Scanner; // Needed for the Scanner class
import java.util.Random; // Needed for the Random class
import java.io.*; // Needed for file I/O classes

 /**
 This program writes random numbers to a file.
 */

 public class ObjectDemo
 {
 public static void main(String[] args) throws IOException
 {
 int maxNumbers; // Max number of random numbers
 int number; // To hold a random number

 // Create a Scanner object for keyboard input.
 Scanner keyboard = new Scanner(System.in);

 // Create a Random object to generate random numbers.
 Random rand = new Random();

 // Create a PrintWriter object to open the file.
 PrintWriter outputFile = new PrintWriter("numbers.txt");

 // Get the number of random numbers to write.
 System.out.print("How many random numbers should I write? ");
 maxNumbers = keyboard.nextInt();

 // Write the random numbers to the file.
 for (int count = 0; count < maxNumbers; count++)
 {
 // Generate a random integer.
 number = rand.nextInt();

 // Write the random integer to the file.
 outputFile.println(number);
 }

 // Close the file.
 outputFile.close();
 System.out.println("Done");
 }
 }

One significant detail to note about Java is that any program is executable when it has a class. Unlike, C++ where the main function is outside of the class, all the functions are inside a class, even the main function. The ObjectDemo class basically writes a specified number of random integers to a file called numbers.txt, and to do this, it creates 3 instances, namely Scanner, PrintWriter, and Random.

When we are working with objects we are using two things:

  • The object itself
  • A reference variable that refers to the object

The object is created in the memory using the new keyword and holds some data to perform some operations. To use the object in the code, we need a reference variable, so for example, if we want to use the Scanner object, we have a reference variable called keyboard. The reference variable does not hold any value. It just holds the object’s memory address. This explanation of object and reference variables can be better explained through a figure.

Object created in memory and reference by a variable

Writing a Simple Class (Step by Step)

Now let’s begin with our first step by step demonstration of creating a class, its variables, and methods. Here we will write our class called rectangle. The class rectangle will have the length and width of the following fields. The rectangle class will also have some functions like getArea.

Let’s begin with our java code for the description.

public class Rectangle
 {
  //keyword private is an access specifier
  private double length;
  private double width;
  
  /**
 The setLength method stores a value in the
 length field.
 @param length The value to store in length.
 */

  public void setLength(double length)
  {
   this.length = length;
  }
 /**
 The setWidth method stores a value in the
 length field.
 @param width The value to store in width.
 */
   public void setWidth(double width)
  {
   this.width = width;
  }

 /**The getArea method returns a Rectangle
 object's area.
 @return The product of length times width
 */
  public void getArea()
  {
  	return length*width;
  }
 }

The private specifier means that we cannot use the variables(length, width) outside the class. The public specifier means that we can call the methods outside of the class.

We will then test the functions written in the rectangle class by creating a main method and then creating an object of rectangle.

/**
 This program demonstrates the Rectangle class's
 setLength and setWidth method.
 */

 public class Demo
 {
 public static void main(String[] args)
 {
 // Create a Rectangle object and assign its
 // address to the box variable.

 Rectangle box = new Rectangle();

 // Indicate what we are doing.
 System.out.println("Sending the value 10.0 " +
 "to the setLength method.");
 System.out.println("Sending the value 20.0 " +
 "to the setWidth method.");

 // Call the box object's setLength method.
 box.setLength(10.0);
 box.setWidth(20.0);
 // Display the area.
 System.out.println("The box's area is " +
 box.getArea());
 // Indicate we are done.
 System.out.println("Done.");
 }
 }
 

The above code must be saved in the same directory as the rectangle class, and then we can run the following command to compile the program.

javac Demo.java

Let’s break down the code to have a deeper understanding of how objects and classes are working—the Statement.

Rectangle box = new Rectangle();

The command declares a variable called box, and the datatype of the variable is a rectangle. The new keyword is used to create an object in memory. After this statement executes, the variable box will reference the object created in memory, as shown.

After we set the length to 10 and set the with to 20 the state of the box object changes.

Avoiding Stale Data

Now you must be wondering why the area of rectangle is not stored, like the length and the width. The area is not stored in a field because it can become stale. When the value of an item depends on another data, and the item is not updated when the data is updated, the item becomes stale.

Constructors

What are constructors? Well, Constructors are a crucial part of a class. A constructor is automatically called when an instance of the class is created. Ever wonder why constructors are called constructors? That’s because they help construct an object. A constructor has the same name as the class and has no return type because constructors are not executed by explicit method calls and cannot return a value.

An example of how constructors work in classes are shown below:

/**
 Rectangle class
 */

 public class Rectangle
 {
  private double length;
  private double width;

 /**
 Constructor
 @param l The length of the rectangle.
 @param w The width of the rectangle.
 */

 public Rectangle(double l, double w)
 {
 length = l;
 width = w;
 }
 }

The constructor shown above is parametrized, and its demonstration is shown in the main function.

/**
 This program demonstrates the Rectangle class's
 constructor.
 */

 public class ConstructorDemo
 {
 public static void main(String[] args)
 {
 // Create a Rectangle object, passing 5.0 and
 // 15.0 as arguments to the constructor.
 Rectangle box = new Rectangle(5.0, 15.0);

 // Display the length.
 System.out.println("The box's length is " +
 box.getLength());

 // Display the width.
 System.out.println("The box's width is " +
 box.getWidth());

 // Display the area.
 System.out.println("The box's area is " +
 box.getArea());
 }
 }

In the demonstration, the length and width are set to 5.0 and 15.0, respectively, and the result of the area comes out to be 5*15 = 75.

A constructor that does not accept arguments is called the no-arg constructor. Therefore, the default constructor is also a no-arg constructor. A default constructor is created when there is no constructor in the class.

UML Diagram

When designing a class, we can use the UML diagram. The UML stands for Unified Modeling Language and depicts classes in an object-oriented system. So what does a UML look like?

UML Skeleton

The first section in the UML holds the class name. The second section has the fields, i.e., the variables, and the third section holds the methods.

UML diagram for the Rectangle class with parameter and data type notation

In the UML diagram, we have some notations. To notify the access specifier of a variable or a method, we have a +, – sign.

// private access specifier depicted by a - sign and datatype is double
-length: double

The variables length and width are private because they start with a – sign and their return type is double.

// public specifier is depicted by a + sign
// function has a return type void
// function takes in argument called length which has a return type double
+ setLength(length:double):void

All the class methods in the UML are public methods as they have a + sign at the start of the method.

Conclusion

That’s all about our introduction tutorial of how objects and classes work in Java. Stay tuned to Code Underscored to keep learning more about Classes and Objects in Java – more guides on the way!

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More