014-007-005

instanceof Operator: Type Checking

Hard

Problem Description

instanceof operator: Type Checking

In this problem, you will create a program that builds an inheritance hierarchy with Shape, Circle, and Rectangle classes, reads shape types from standard input to create objects, uses the instanceof operator to check the type of each object, and displays the results to standard output.

Learning Objective: Understand how to check object types using instanceof operator

Overview

The instanceof operator checks whether an object is an instance of a specific class or interface. Used for type checking in inheritance hierarchies, it's important as a precondition for safe downcasting.

Specifications

Create parent class Shape:

  • draw() method: outputs "Drawing shape"

Create child class Circle:

  • Extends Shape
  • Override draw(): outputs "Drawing circle"
  • Unique method getRadius(): outputs "Radius: 5"

Create child class Rectangle:

  • Extends Shape
  • Override draw(): outputs "Drawing rectangle"
  • Unique method getDimensions(): outputs "Width: 10, Height: 20"

In Main class:

  • Read the number of shapes n from standard input
  • Read n lines each containing a shape type ("circle", "rectangle", or "shape")
  • Create the corresponding object for each type and store in a Shape array
  • For each element, check if it's Circle using instanceof
  • If Circle: output "This is a circle" and call getRadius()
  • Otherwise: output "Not a circle"

Input Format

n
type1
type2
...
typeN
  • n: number of shapes (1 or more)
  • typei: one of "circle", "rectangle", or "shape"

Output Format

For each shape:

  • If Circle: output "This is a circle" then "Radius: 5"
  • Otherwise: output "Not a circle"

Sample Input/Output

Input:

3
circle
rectangle
shape

Output:

This is a circle
Radius: 5
Not a circle
Not a circle

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up