OOPs, Classes, Methods
RECTANGLE DIMENSION CHANGE - INSTANCEOF OPERATOR
Sample Input and Output :
Enter the length of the rectangle
5
Enter the width of the rectangle
6
Rectangle Dimension
Length:5
Width:6
Area of the Rectangle:30
Enter the new dimension
2
Rectangle Dimension
Length:10
Width:12
Area of the Rectangle:120
5
Enter the width of the rectangle
6
Rectangle Dimension
Length:5
Width:6
Area of the Rectangle:30
Enter the new dimension
2
Rectangle Dimension
Length:10
Width:12
Area of the Rectangle:120
CODE:
public class Rectangle {
private int length;
private int width;
private int area;
private int newlen;
private int newwid;
private int newarea;
public Rectangle(int l, int w) {
this.length=l;
this.width=w;
}
public int area() {
area=length*width;
return area;
}
public void display(){
System.out.println("Rectangle Dimension");
System.out.println("Length:"+length);
System.out.println("Width:"+width);
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
Rectangle dimensionChange(int newDimension){
newlen=length*newDimension;
newwid=width*newDimension;
newarea=newlen*newwid;
return new Rectangle(newlen,newwid);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the length of the rectangle");
int len=sc.nextInt();
System.out.println("Enter the width of the rectangle");
int wid=sc.nextInt();
Rectangle r1 = new Rectangle(len,wid);
r1.display();
int area=r1.area();
System.out.println("Area of the Rectangle:"+area);
System.out.println("Enter the new dimension");
int newDimension=sc.nextInt();
//here, r1 in LHS is the returned rectangle object from the method
r1=r1.dimensionChange(newDimension);
if(r1 instanceof Rectangle==true) {
r1.display();
area=r1.area();
System.out.println("Area of the Rectangle:"+area);
}
}
}
Comments
Post a Comment