In: Computer Science
What does the super keyword represents and where can it be used? Give an example of a superclass and subclass. Be sure to make all the instances variables of the super class private. Include at least one constructor in each class and ensure that the constructor of the subclass calls the constructor of the superclass. Also include a toString method in both classes that returns the values of the instance variables with appropriate labels. Ensure that the toString method of subclass calls the toString method of the superclass so that the string returned contains the values of all the inherited instance variables.
//Shape.java public class Shape { // instance variable private String shapeName; // Super class constructor public Shape(String shapeName) { this.shapeName = shapeName; } public String toString() { return "Shape{" + "shapeName='" + shapeName + '\'' + '}'; } }
///////////////////////////////////////////////////////////
//Circle.java public class Circle extends Shape { private double radius; //Subclass constructor public Circle(double radius) { // constructor of the subclass calls the constructor of the superclass super("Circle"); this.radius = radius; } // toString method of subclass calls the toString method of the superclass public String toString() { return super.toString()+"\n"+"Circle{" + "radius=" + radius + '}'; } }
///////////////////////////////////////////////////////////
//TestCircle.java public class TestCircle { public static void main(String[] args) { Circle circle = new Circle(5); System.out.println(circle); } }
Shape{shapeName='Circle'} Circle{radius=5.0}