Question: create a sub-class in Java, and use inheritance, super, and override. Steps 1. Create a class called Square. It should have a single protected variable
create a sub-class in Java, and use inheritance, super, and override.
Steps 1. Create a class called Square. It should have a single protected variable of type int called width.
2. Create three constructors: an empty constructor with no parameters, a default constructor with initial width as its parameter, and copy constructor with a Square object as its parameter.
3. Write the get/set methods for width.
4. Write the equals( ) and toString( ) methods.
5. Write a function getArea( ), which returns the calculation of the surface area as an int.
6. Write a function getCircumference( ), which returns the is the total length of the enclosing boundary, which is the sum of all four sides.
7. Write a function, printCalculations(), which prints out the results of getArea(), and getCircumference() functions using System.out.
8. Create a subclass of Square, called Rectangle. It should have an extra variable called height.
9. Repeat steps 4-6 for the new Rectangle class, but update the functions to use the width and height. Also create the empty, default, and copy constructors for the Rectangle class. Use this() and super() wherever possible to minimize code duplication. For step 3, add getters and setters for height.
10. Create a main function to launch the program.
Put the following code in the main method:
Square sq = new Square(10); Rectangle rect = new Rectangle(5, 10);
System.out.println("sq is:" + sq.toString() );
System.out.println("rect is:" + rect); //Notice there is no .toString().
The compiler puts it there for you. sq.printCalculations( ); rect.printCalculations( );
Square otherSquare = new Square(sq);
System.out.println("Does sq == sq:" + (sq == sq) );
System.out.println("Does otherSquare == sq:" + (otherSquare == sq) );
System.out.println("Does otherSquare.equals(sq):" + (otherSquare.equals(sq) );
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
