In: Computer Science
white a class having two private variables and one member function which will return the area of rectangle
This code is written in Java language.
There are following Components present in Code.
1. A class named Rectangle.
2. Two private variables i.e length and breadth
3.A constructor with two parameters to set the values of length and breadth.
4. member function getArea() which will return area of rectangle.
5. A main class to test the code.
Following is the code which is saved in Rectangle.java
Comments are added to give an idea about what code is doing.
// A class with name Rectangle
public class Rectangle {
// Two private variables
private int length;
private int breadth;
// Constructor to set the values
public Rectangle(int x, int y) {
length = x;
breadth = y;
}
// function which will return Area of rectangle i.e length*breadth
public int getArea() {
return length * breadth;
}
public static void main(String[] args) {
// Creating a Rectangle with Length = 10 and Breadth = 5
Rectangle rec = new Rectangle(10, 5);
System.out.println("Area of rectangle is " + rec.getArea());
}
}
When you will run above code, output will be like following :
Please let us know in comments if you have any doubt in above solution.