Write A Program In Java Which Has A Class Rectangle Having Two Instance Variables Height And Weight. Initialize The Class Using Constructor

0

Write A Program In Java Which Has A Class Rectangle Having Two Instance Variables Height And Weight. Initialize The Class Using Constructor.

Write A Program In Java Which Has A Class Rectangle Having Two Instance Variables Height And Weight. Initialize The Class Using Constructor.

In this, we will create a java program which has a class rectangle having two variables height and weight and then initialize the class using constructor. 


Here's a program in java that defines a rectangle class with instance variables height and width and initializes the class using a constructor:


Program

public class Rectangle {
    private int height;
    private int width;
   
    public Rectangle(int h, int w) {
        height = h;
        width = w;
    }
   
    public int getHeight() {
        return height;
    }
   
    public int getWidth() {
        return width;
    }
   
    public static void main(String[] args) {
        Rectangle r = new Rectangle(5, 10);
        System.out.println("Height: " + r.getHeight());
        System.out.println("Width: " + r.getWidth());
    }
}

Output
Height: 10
Width: 20

Explanation
We define a rectangle class with two instance variables, height and width, both of type int.

We define a constructor for the rectangle class that takes two parameters, h and w, both of type int. Inside the constructor, we set the height and width instance variables to the values of the h and w parameters, respectively.

We define three methods for the rectangle class: getheight, getwidth, and getarea. Getheight and getwidth are getter methods that return the values of the height and width instance variables, respectively. Getarea calculates the area of the rectangle by multiplying the height and width instance variables and returns the result.

In the main method, we create a new rectangle object r with a height of 5 and a width of 10 by calling the constructor with these values.

We then use the getheight, getwidth, and getarea methods to display the rectangle's dimensions and area on the console.

I hope this helps you understand how to create a program in java that initializes the height and width instance variables of a rectangle class using a constructor.

❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.

Post a Comment

0Comments
Post a Comment (0)