Construct a class called Rectangle. A Rectangle has both a length and a width (both positive integers). Access to them should be only inside the class and within the inheritance hierarchy. Then implement the following:
Square construction prints "Square Constructor" and accepts one integer which is the length of a side. The version of the area and perimeter of Square prints "Square Area" and "Square Perimeter", respectively.
Input
A positive integer representing the length of the side of a Square.
2
Output
The message of the constructors when called, the area, and perimeter of Square.
Rectangle·Constructor
Square·Constructor
Square·Area
Area:·4
Square·Perimeter
Perimeter:·8
import java.util.Scanner;
class Rectangle {
private int length;
private int width;
/***
* constructor that accepts two integers for the length and the width. Prints
* "Rectangle Constructor"
*
* @param length
* @param width
*/
public Rectangle(int length, int width) {
System.out.println("Rectangle Constructor");
this.length = length;
this.width = width;
}
/***
* area - prints "Rectangle Area" and returns the area of the rectangle
*
* @return
*/
public int area() {
System.out.println("Rectangle Area");
return this.length * this.width;
}
/**
* perimeter - prints "Rectangle Perimeter" and returns the perimeter of the
* rectangle
*
* @return
*/
public int perimeter() {
System.out.println("Rectangle Perimeter");
return 2 * (this.length + this.width);
}
/**
* @return the length
*/
public int getLength() {
return length;
}
/**
* @param length the length to set
*/
public void setLength(int length) {
this.length = length;
}
/**
* @return the width
*/
public int getWidth() {
return width;
}
/**
* @param width the width to set
*/
public void setWidth(int width) {
this.width = width;
}
}
class Square extends Rectangle {
public Square(int length) {
super(length, length);
System.out.println("Square Constructor");
}
/***
* area - prints "Square Area" and returns the area of the Square
*
* @return
*/
public int area() {
System.out.println("Square Area");
return this.getLength() * this.getLength();
}
/**
* perimeter - prints "Square Perimeter" and returns the perimeter of the Square
*
* @return
*/
public int perimeter() {
System.out.println("Square Perimeter");
return 2 * (this.getLength() + this.getLength());
}
}
class App {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Inpu A positive integer representing the length of the side of a Square.
int length = scanner.nextInt();
Square square = new Square(length);
System.out.println("Area: " + square.area());
System.out.println("Perimeter: " + square.perimeter());
scanner.close();
}
}
Comments
Leave a comment