Problem :7.4


 Question 7.4 : Create a class named 'Rectangle' with two data members 'length' and 'breadth' and two methods to print the area and perimeter of the rectangle respectively. Its constructor having parameters for length and breadth is used to initialize length and breadth of the rectangle. Let class 'Square' inherit the 'Rectangle' class with its constructor having a parameter for its side (suppose s) calling the constructor of its parent class as 'super(s,s)'. Print the area and perimeter of a rectangle and a square.


Solution:

//Main Class

package com.company;
import java.util.Scanner;
public class Main {

    public static void main(String[] args) {
        Scanner obj = new Scanner(System.in);
        System.out.print("Enter lenght: ");
        int length = obj.nextInt();
        System.out.print("Enter breadth: ");
        int breadth = obj.nextInt();
        Rectangle r = new Rectangle(length,breadth);
        r.Area();
        r.perimeter();
        System.out.print("Enter the Square: ");
        int square = obj.nextInt();
        Square s = new Square(square);
        s.Area();
        s.perimeter();

    }
}


//Rectangle class

package com.company;
public class Rectangle {
    public int length;
    public int breadth;
    Rectangle(){

    }
    public Rectangle(int length,int breadth) {
        this.length = length;
        this.breadth = breadth;
    }
    public void Area(){
        System.out.println(this.breadth*this.length);
    }
    public void perimeter(){
        System.out.println(2*(length+breadth));

    }

}


//Square Class

package com.company;

public class Square extends Rectangle{

    public Square(int s){
        super(s,s);
    }
}

Previous Post Next Post