Write a program called InheritanceTest.java to support an inheritance hierarchy
ID: 3531986 • Letter: W
Question
Write a program called InheritanceTest.java to support an inheritance hierarchy for class Point-Square-Cube. Use Point as the superclass of the hierarchy. Specify the instance variables and methods for each class. The private variable of Point should be the x-y coordinates. The private data of Square should be the sideLength. The private data of Cube should be depth. Each class must provide applicable accessor, mutator, and toString() methods for manipulating private variables of each corresponding class. In addition, the Square class must provide the area() and perimeter() methods. The Cube must provide the area() and volume() methods.
Write a program that instantiates objects of your classes, ask the user to enter the value for x, y, and sideLength, test all instance methods and outputs of each object
Explanation / Answer
Below is a rough(ish) example, you'll need to add a bit more but it's a good start. I also wrapped the Point, Square and Point classes within InheritanceTest and also intentionally left out constructors, which you can write yourself!
public class InheritanceTest {
..public class Point {
....private int x, y;
..}
..public class Square extends Point {
....private int sideLength;
..}
..public class Cube extends Square {
....private int depth;
..}
}
Also, don't forget to remove the '.' and replace with a ' '!
You could look at the above example like this:
..InheritanceTest [Point -> Square -> Cube]
Where '[' and ']' means contains in, and '->' means derived from.
Note the keyword 'extends', which is used after a class name to denote the class is derived from an existing class, which is the class name that follows.
You could potentially use the following as constructors, respectively:
..public Point (int x, int y){
....this.x = x;
....this.y = y;
..}
..public Square (int x, int y, int length){
....super(x, y)
....this.sideLength = length;
..}
..public Cube (int x, int y, int length, int depth){
....super(x, y, length);
....this.depth = depth);
..}
Note the use of the keyword 'super' to access the parent class of the derived instance. It's also important to use the 'this' keyword when accessing parameters of the class that share the same name as a parameter of a method (in this case, the constructor).
I hope this helps to clear any confusion you may have and enjoy programming!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.