Create an abstract class Shape. It contains two attributes: x and y, which indic
ID: 3882517 • Letter: C
Question
Create an abstract class Shape. It contains two attributes: x and y, which indicate the coordinates in the 2-dimensional coordinate axis. It also has a method called area(), which is designed to display the area of the shape. Based on the Shape class, design a class named Circle with radius r and a class named Square with length of side l. They need to implement their area() methods. Create a Test class to instantiate a Circle object c with radius of 5 and a Square object s with length of side of 10. Their coordinates are randomly selected. Print their area in polymorphism form.
Explanation / Answer
///abstract base class Shape
abstract class Shape
{
public int x,y;
public abstract double area();
}
class Circle extends Shape //inheritance
{
public Circle(int radius) //constructor
{
x = radius;
}
public double area()
{
return 3.14*x*x;
}
public String toString()
{
return " Circle : Area :"+ area() +" square units";
}
}
class Square extends Shape
{
public Square(int side)
{
x = side;
}
public double area()
{
return x*x;
}
public String toString()
{
return " Square : Area :"+ area()+" square units" ;
}
}
class Test
{
public static void main(String[]args)
{
// Create circle r = 5
Circle c1 = new Circle(5);
System.out.println(c1);
// Create square wtih s=10
Square s1 = new Square(10);
System.out.println(s1);
}
}
Output:
Circle : Area :78.5 square units
Square : Area :100.0 square units
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.