Example: Defining Classes and Creating Objects
Tags: java, programming, learning, beginners
Published: 2024-06-03 17:09:32

Classes are definitions for objects and objects are created from classes. This section gives two examples of defining classes and uses the classes to create objects. Below is a program that defines the **Circle** class and uses it to create objects. The program constructs three circle objects with radius **1**, **25**, and **125** and displays the radius and area of each of the three circles. It then changes the radius of the second object to **100** and displays its new radius and area.

```
package demo;

public class TestSimpleCircle {

	public static void main(String[] args) {
		// Create a circle with radius 1
		SimpleCircle circle1 = new SimpleCircle();
		System.out.println("The area of the circle of radius " + circle1.radius + " is " + circle1.getArea());
		
		// Create a circle with radius 25
		SimpleCircle circle2 = new SimpleCircle(25);
		System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());
		
		// Create a circle with radius 125
		SimpleCircle circle3 = new SimpleCircle(125);
		System.out.println("The area of the circle of radius " + circle3.radius + " is " + circle3.getArea());
		
		// Modify circle radius
		circle2.radius = 100; // or circle2.setRadius(100)
		System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());
	}

}

	// Define the circle class with two constructors
	class SimpleCircle {
		double radius;
		
		/** Construct a circle with radius 1 */
		SimpleCircle(){
			radius = 1;
		}
		
		/** Construct a circle with a specified radius */
		SimpleCircle(double newRadius){
			radius = newRadius;
		}
		
		/** Return the area of this circle */
		double getArea() {
			return radius * radius * Math.PI;
		}
		
		/** Return the perimeter of this circle */
		double getPerimeter() {
			return 2 * radius * Math.PI;
		}
		
		/** Set a new radius for this circle */
		void setRadius(double newRadius) {
			radius = newRadius;
		}
	}


```

`The area of the circle of radius 1.0 is 3.141592653589793
The area of the circle of radius 25.0 is 1963.4954084936207
The area of the circle of radius 125.0 is 49087.385212340516
The area of the circle of radius 100.0 is 31415.926535897932`

The program contains two classes. The first of these, **TestSimpleCircle**, is the main class. Its sole purpose is to test the second class, **SimpleCircle**. Such a program that uses the class is often referred to as a _client_ of the class. When you run the program, the Java runtime system invokes the **main** method in the main class.

You can put the two classes into one file, but only one class in the file can be a _public class_. Furthermore, the public class must have the same name as the file name. Therefore, the file name is **TestSimpleCircle.java**, since **TestSimpleCircle** is public. Each class in the source code is compiled into a **.class** file. When you compile **TestSimpleCircle.java**, two class files **TestSimpleCircle.class** and **SimpleCircle.class** are generated, as shown below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/saksh88m4qglqtx7diry.png)

The main class contains the **main** method (line 5) that creates three objects. As in creating an array, the **new** operator is used to create an object from the constructor: **new SimpleCircle()** creates an object with radius **1** (line 7), **new SimpleCircle(25)** creates an object with radius **25** (line 11), and **new SimpleCircle(125)** creates an object with radius **125** (line 15).

These three objects (referenced by **circle1**, **circle2**, and **circle3**) have different data but the same methods. Therefore, you can compute their respective areas by using the **getArea()** method. The data fields can be accessed via the reference of the object using **circle1.radius**, **circle2.radius**, and **circle3.radius**, respectively. The object can invoke its method via the reference of the object using **circle1.getArea()**, **circle2.getArea()**, and **circle3.getArea()**, respectively.

These three objects are independent. The radius of **circle2** is changed to **100** in line 19. The object’s new radius and area are displayed in lines 20.

As another example, consider television sets. Each TV is an object with states (current channel, current volume level, power on or off) and behaviors (change channels, adjust volume, turn on/off). You can use a class to model TV sets. The UML diagram for the class is
shown below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z22npi065j3702rtoulf.png)

```
package demo;

public class TV {
	int channel = 1; // Default channel is 1
	int volumeLevel = 1; // Default volume level is 1
	boolean on = false; // TV is off
	
	public TV() {
	}
	
	public void turnOn() {
		on = true;
	}
	
	public void turnOff() {
		on = false;
	}
	
	public void setChannel(int newChannel) {
		if(on && newChannel >= 1 && newChannel <= 120)
			channel = newChannel;
	}
	
	public void setVolume(int newVolumeLevel) {
		if(on && newVolumeLevel >= 1 && newVolumeLevel <= 7)
			volumeLevel = newVolumeLevel;
	}
	
	public void channelUp() {
		if(on && channel < 120)
			channel++;
	}
	
	public void channelDown() {
		if(on && channel > 1)
			channel--;
	}
	
	public void volumeUp() {
		if(on && volumeLevel < 7)
			volumeLevel++;
	}
	
	public void volumeDown() {
		if(on && volumeLevel > 1)
			volumeLevel--;
	}
}

```

The constructor and methods in the **TV** class are defined public so they can be accessed from other classes. Note that the channel and volume level are not changed if the TV is not on. Before either of these is changed, its current value is checked to ensure that it is within the correct range. Below gives a program that uses the **TV** class to create two objects.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4xueinwua3h7cbwvvvg.png)

The program creates two objects in lines 6 and 11 and invokes the methods on the objects to perform actions for setting channels and volume levels and for increasing channels and volumes. The program displays the state of the objects in lines 17–18. The methods are invoked using syntax such as **tv1.turnOn()** (line 7). The data fields are accessed using syntax such as **tv1.channel** (line 17).

These examples have given you a glimpse of classes and objects. You may have many questions regarding constructors, objects, reference variables, accessing data fields, and invoking object’s methods. The sections that follow discuss these issues in detail.