Saturday, January 30, 2021

SKP's Java Problem Solving Series : Simple Java Inheritance (OOPs)

[Question/Problem Statement is the Property of Techgig]
Java Inheritance / Simple OOPs [] 
Create Two Classes:

The Rectangle class should have two data fields-width and height of int types. The class should have display()method, to print the width and height of the rectangle separated by space.

The RectangleArea class is Derived from Rectangle class, i.e., it is the Sub-Class of Rectangle class. The class should have read_input() method, to Read the Values of width and height of the Rectangle. The RectangleArea class should also Overload  the display() Method to Print the Area (width*height) of the Rectangle.

Input Format
The First and Only Line of Input contains two space separated Integers denoting the width and height of the Rectangle.

1 <= width,height <= 10^3

Output Format
The Output Should Consist of Exactly Two Lines.
In the First Line, Print the Width and Height of the Rectangle Separated by Space. 
In the Second Line, Print the Area of the Rectangle.

[Explanation of the Solution]
This is the Simplest of all OOPs Questions! Demonstration of Inheritance and Overriding (Very Loosely, Liskov Substitution of SOLID). 

[Source Code, Sumith Puri (c) 2021 - Free to Use & Distribute]
  * Techgig Core Java Basics Problem - Get Simple OOPs Right!  
  * Author: Sumith Puri [I Bleed Java!]; GitHub: @sumithpuri;  
  import java.util.*;   
  class Rectangle {  
    private int width;  
    private int height;  
    public void display() {  
      System.out.println(width + " " + height);  
    public int getWidth() {  
      return width;  
    public void setWidth(int width) {  
    public int getHeight() {  
      return height;  
    public void setHeight(int height) {  
  class RectangleArea extends Rectangle {  
    public void read_input() {  
     Scanner scanner = new Scanner (;   
    public void display() {  
  public class CandidateCode {   
   public static void main(String args[] ) throws Exception {   
     RectangleArea rectangleArea = new RectangleArea();  

Happy Problem Solving using Java!

No comments: