Write a program to print the area of two rectangles having sides (4,5) and (5,8) respectively by creating a class named ‘Rectangle’ with a method named ‘Area’ which returns the area and length and breadth passed as parameters to its constructor.
Solution
import java.util.*; class Rectangle { int len; int bre; Rectangle(int l, int b) { len=l; bre=b; } public int getArea(){ return len*bre; } public int getPerimeter(){ return 2*(len+bre); } } class Shape { public static void main(String args[]) { Rectangle ob1=new Rectangle(4,5); Rectangle ob2=new Rectangle(5,8); System.out.println("Area is "+ob1.getArea()+" Perimeter is "+ob1.getPerimeter()); System.out.println("Area is "+ob2.getArea()+" Perimeter is "+ob2.getPerimeter()); } }
Save the above Program with “Shape.Java” then compile it with the following commands:
javac Shape.java //to compile the code java Shape // to run the code
Output is :
Area is 20Perimeter is 18 Area is 40Perimeter is 26