Write a Java application that solves a problem. Your program must include: 1. Co
ID: 3535252 • Letter: W
Question
Write a Java application that solves a problem. Your program must include:
1. Composition
2. Abstract Class
3. Inheritance
4. Polymorphism
Note:
Documentation will be considered as part of the grade. In your documentation you should include:
1. A General Description of the Problem you are solving.
2. Inheritance Hierarchy Chart.
3. Indicate where Composition is used.
4. Indicate which class is an Abstract Class.
5. Indicate which functions are Overridden.
6. Indicate where Polymorphism is used in your application.
Explanation / Answer
// we will write a program that will calculate area of different shapes
//we will use a total of 4 java classes, 1 super class, 2 base classes and 1 driver program
//working code
/
/shape.java an abstract class
abstract public class Shape {
// Private member variable
private String color;
// Constructor
public Shape (String color) {
this.color = color;
}
@Override
public String toString() {
return "Shape of color="" + color + """;
}
// All Shape subclasses must implement a method called getArea()
abstract public double getArea(); //polymorphism
}
//2nd rectangle.java
// Define Rectangle, subclass of Shape
public class Rectangle extends Shape {
// Private member variables
private int length;
private int width;
// Constructor
public Rectangle(String color, int length, int width) {
super(color);
this.length = length;
this.width = width;
}
@Override
public String toString() {
return "Rectangle of length=" + length + " and width=" + width + ", subclass of " + super.toString();
}
@Override
public double getArea() {
return length*width;
}
}
//3rd Triangle.java
// Define Triangle, subclass of Shape
public class Triangle extends Shape {
// Private member variables
private int base;
private int height;
// Constructor
public Triangle(String color, int base, int height) {
super(color);
this.base = base;
this.height = height;
}
@Override
public String toString() {
return "Triangle of base=" + base + " and height=" + height + ", subclass of " + super.toString();
}
@Override
public double getArea() {
return 0.5*base*height;
}
}
// A test driver program for Shape and its subclasses
public class TestShape {
public static void main(String[] args) {
Shape s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());
Shape s2 = new Triangle("blue", 4, 5);
System.out.println(s2);
System.out.println("Area is " + s2.getArea());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.