Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Creating Class and Object in Java

 

 

In this lesson, you will learn.

  • Defining a Class
  • Declaring a Class
  • Adding Fields and Methods in a Class
  • Creating Object of a Class
  • Accessing Members of a Class
  • Examples

 

Defining a Class

  • A class is described as the blueprint or template from which the object is made.
  • Anything you wish to represent in the Java program must be encapsulated in a class that defines the state/characteristics and behavior of a basic program known as an object.
  • A class creates an object(real-world entity) and an object uses a method to communicate between them.

 

Example

A dog is a class that defines characteristics like color, length, height, weight, breed, etc., and behaviors like jumping, barking, sleeping, walking, shaking, etc.

These characteristics are known as the member variables, and the behavior is specified by methods.

 

Declaring a Class

A class in Java is declared by the use of the class keyword.

 

Syntax

class <class-name>
{
       //Fields
       datatype instance-var1;
       datatype instance-var2;
       ----------------------
       ----------------------
       datatype instance-varN;

       // Constructor
       ClassName() {
           // Constructor body
       }

       //Methods
       datatype methodName1(parameter-list)
       {
           //Method Body
       }

       // ..........

       datatype methodNameN(parameter-list)
       {
           //Method Body
       }
}

 

The data, or variables, defined within a class are called instance variables and the code is contained within methods.

Collectively, the methods, variables, and constructors defined within a class are called class members.

Constructor: A special method that is called when an instance (object) of the class is created. Constructors have the same name as the class and do not have a return type.

 

Important Note!

Constructors are discussed in upcoming lessons.

 

Note: Variables defined within a class are called instance variables because each instance of the class (i.e., each object of the class) contains a separate copy of instance variables.

Example: Adding Fields and Method inside a Class

 

class Rectangle
{
    //Fields declaration
    double length;
    double width;
    
    // Method to display Rectangle Dimensions
    void displayDimensions() 
    {
        System.out.println("Length: "+length);
        System.out.println("Width: " +width);
    }
}

Here ‘Rectangle’ is a class that defines two instance variables: length, and width. We have added a method named displayDimensions() to display the dimensions of a rectangle.

 

Creating an Object of a Class

An object is an instance of a class and has a unique identity. The following code snippet shows how to declare an object of a class.

Syntax: Declaring an object

class-name object-name;

 

Example

Rectangle r1; //r1 is an object name

The above code only declares an object not allocating the memory to it. To allocate memory to the object, you need to instantiate the object by using the ‘new’ operator.

The ‘new’ operator allocates memory to an object. It also returns a reference to that memory location in the object variable.

The following code snippet shows how to instantiate an object.

Instantiate an Object

r1 = new Rectangle(); //r1 is an object name

Now, an object r1 is an instance of the Rectangle class. Thus, it is a “physical” reality and holds space for its member variables.

You can declare and instantiate an object using a single statement as follows.

Rectangle rect1 = new Rectangle(); //rect1 is an object name

 

There is no limitation on creating objects of a class. You can create multiple objects of a class.

Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle();
//........
Rectangle rectN = new Rectangle();

 

When you create an instance (i.e. object) of a class then each object contains a separate copy of each instance variable defined by the class.

Thus, every Rectangle object(rect1, rect2, ……rectN) will contain its separate copies of the instance variable i.e. length, and width as shown in the below figure.

What’s the difference between a class and an object?

A class is not an object. (but it’s used to construct them)

 

A class is a blueprint for an object. It tells the virtual machine how to make an object of that particular type.

Each object made from that class can have its own values for the instance variables of that class.

For example, you might use the Button class to make dozens of different buttons, and each button might have its color, size, shape, label, and so on.

 

Accessing Class members(Instance Variables and Method)

The Dot Operator (.)

The dot operator (.) gives you access to an object’s state and behavior (instance variables and methods).

Syntax

objectname.members; //members may be variable or method

 

Example

//Accessing and assigning value to a instance variables
rect1.length=10.0;
rect1.width=15.5;

//Accessing method
rect1.displayDimensions();

 

Example 1: Creating a Rectangle Class

package ch7;

public class RectangleExample1 {
	
	//Fields declaration
    double length;
    double width;
     
    // Method to display Rectangle Dimensions
    void displayDimensions() 
    {
        System.out.println("Length: "+length);
        System.out.println("Width: " +width);
    }

	public static void main(String[] args) {
		RectangleExample1 rect1=new RectangleExample1();
		rect1.length=3.0;
		rect1.width=4.0;
		rect1.displayDimensions();
	}
}

 

Output

Length: 3.0
Width: 4.0

 

Explanation: This Rectangle class has two fields (length and width), a method displayDimensions() displays the Rectangle’s length and width. The main method creates an object rect1 of class Rectangle and calls the displayDetails() method.

 

Method Returning a Value and Creating Multiple Objects

 

 

Example 2: Method Returning a Value and Creating Multiple Objects

<pre class="wp-block-syntaxhighlighter-code"><br />package ch7;

public class RectangleExample2 {

	//Fields declaration
    double length;
    double width;
     
    // Method to display area
    double findArea(){
    	return length*width;
    }

	public static void main(String[] args) {
		
		RectangleExample2 rect1=new RectangleExample2();
		RectangleExample2 rect2=new RectangleExample2();
		
		//Set the dimensions of rect1
		rect1.length=3.0;
		rect1.width=4.0;
		double area;
		area=rect1.findArea();
		System.out.println("Area of Rectangle 1: "+area);
		
		//Set the dimensions of rect2
		rect2.length=10.0;
		rect2.width=15.0;
		area=rect2.findArea();
		System.out.println("Area of Rectangle 2: "+area);
	}
}
</pre>

 

 

Output

Area of Rectangle 1: 12.0
Area of Rectangle 2: 150.0

 

Creating Multiple Java Classes in Eclipse

 

 

Example 3: Creating Multiple Java Classes

 

package ch7;

//Creating a Circle class
class Circle {
    double radius; // instance variable

    double calculateArea() {
        return Math.PI * radius * radius;
    }
}

//Creating a Rectangle class
class Rectangle{
	double length, width;
	double findArea() {
		return length*width;
	}
}

public class CircleMain {
    public static void main(String[] args) {
        // Creating the first Circle object and initializing its radius
        Circle circle1 = new Circle();
        circle1.radius = 5.0;
        
        // Creating the first Rectangle object and initialize its dimensions
        Rectangle rect1=new Rectangle();
        rect1.length=4.0;
        rect1.width=3.0;

        // Creating the second Circle object and initializing its radius
        Circle circle2 = new Circle();
        circle2.radius = 10.0;
        
        // Creating the 2nd Rectangle object and initialize its dimensions
        Rectangle rect2=new Rectangle();
        rect2.length=10.0;
        rect2.width=15.0;

        // Calculating and displaying the areas
        System.out.println("Area of circle1: " + circle1.calculateArea());
        System.out.println("Area of circle2: " + circle2.calculateArea());
        System.out.println("Area of rect1: " + rect1.findArea());
        System.out.println("Area of rect2: " + rect2.findArea());
        
    }
}

 

Output

Area of circle1: 78.53981633974483
Area of circle2: 314.1592653589793
Area of rect1: 12.0
Area of rect2: 150.0

Example 4: Adding a Method That Takes Parameters

package ch7;

class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    int multiply(int a, int b) {
        return a * b;
    }
}

public class CalculatorMain {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println("Addition: " + calc.add(5, 3));
        System.out.println("Multiplication: " + calc.multiply(4, 2));
    }
}

 

Output

Addition: 8
Multiplication: 8

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review

 

 

Layer 1
Login Categories