Flowers on planet Galax come in two shapes: round and triangular. Both have the
ID: 3703185 • Letter: F
Question
Flowers on planet Galax come in two shapes: round and triangular. Both have the same range of colors (orange, green, or purple); the round ones also have a scent (rose or lavender) while the square ones emit a sound (squeak or creak). Their size is calculated by computing the area of the shape (? r2 for the circles, base * height / 2 for the triangles). You decide to use these floral facts to illustrate how inheritance works. Using the following program: public class Flowers { public static void main (String [] args) { Flower r = new Round("orange", "lavender", 3); Flower t = new Triangular("purple", "squeak", 5, 4); Flower [] floral = {r, t}; for (Flower f: floral) { System.out.println(f); System.out.printf("size %.2f ", f.computeSize()); } } } to generate output like this: color orange scent lavender radius 3 size 28.27 color purple sound squeak base 5 height 4 size 10.00 you create an abstract superclass Flower and two subclasses Round and Triangular, each containing instance variables, an argument constructor, getters, setters, and toString() and computeSize() methods….
superclass
subclasses
Explanation / Answer
Flowers.java
public class Flowers {
public static void main(String[] args) {
Flower r = new Round("orange", "lavender", 3);
Flower t = new Triangular("purple", "squeak", 5, 4);
Flower[] floral = { r, t };
for (Flower f : floral) {
System.out.println(f);
System.out.printf("size %.2f ", f.computeSize());
}
}
}
abstract class Flower {
private String color,scent ;
public Flower(String color,String scent) {
this.color=color;
this.scent=scent;
}
public abstract double computeSize();
public String toString() {
return "color "+color+" scent "+scent;
}
}
class Round extends Flower {
private int radius;
public Round(String color,String scent,int radius) {
super(color, scent);
this.radius = radius;
}
public double computeSize() {
return Math.PI*radius*radius;
}
public String toString() {
return super.toString()+" radius "+radius;
}
}
class Triangular extends Flower {
private int a,b;
public Triangular(String color,String scent, int a, int b) {
super(color, scent);
this.a = a;
this.b=b;
}
public double computeSize() {
return (a * b)/2.0;
}
public String toString() {
return super.toString()+" base "+a+" height "+b;
}
}
Output:
color orange scent lavender radius 3
size 28.27
color purple scent squeak base 5 height 4
size 10.00
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.