Java Program: Design an interface named Colorable with a void method named howTo
ID: 3806441 • Letter: J
Question
Java Program:
Design an interface named Colorable with a void method named howToColor(). Every class of a colorable object must implement the Colorable interface. Design a class named Square that extends GeometricObject and implements Colorable. Implement howToColor to display the message Color all four sides. The Square class has a private double data field named side with its getter and setter methods. It has a no-arg constructor to create a Square with side 1 and another constructor that creates a Square with a specified side.
Write a test program that creates an array of five GeometricObjects. For each object in the array, display its area and invoke its howToColor method if it is colorable.
Explanation / Answer
Colorable.java
public interface Colorable {
String howToColor();
}
________________
GeometricObject.java
public abstract class GeometricObject {
public abstract double area();
}
__________________
Square.java
public class Square extends GeometricObject implements Colorable {
double side;
public Square(double side) {
super();
this.side = side;
}
@Override
public String howToColor() {
return "Color All four sides";
}
public double area()
{
return side*side;
}
}
________________
Rectangle.java
public class Rectangle extends GeometricObject {
private double length;
private double width;
public Rectangle(double length, double width) {
super();
this.length = length;
this.width = width;
}
public double area() {
return length * width;
}
}
_______________
Circle.java
public class Circle extends GeometricObject {
private double radius;
public Circle(double radius) {
super();
this.radius = radius;
}
public double area() {
return Math.PI * radius * radius;
}
}
________________
Test.java
public class Test {
public static void main(String[] args) {
GeometricObject[] go={new Square(2), new Circle(5), new Square(5), new Rectangle(3, 4),new Square(4.5)};
for(int i=0;i<go.length;i++)
{
System.out.printf(" Area is %.2f ",go[i].area());
if(go[i] instanceof Colorable)
System.out.println(((Colorable)go[i]).howToColor()+" ");
}
}
}
_________________
Output:
Area is 4.00
Color All four sides
Area is 78.54
Area is 25.00
Color All four sides
Area is 12.00
Area is 20.25
Color All four sides
____________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.