1

Java Inheritance: Question regarding the parent reference variable.

I am learning Java and going through the inheritance problems in Java, have one question here.

public class Shape {
    private String shapeName;
    private String area;
    //normal getters and setters
}

public class Triangle extends Shape {
    private String typeOfTriangle;
    //normal getter and setter.
}

public class ShaperRunner {
    public static void main(String[] args) {
        Shape shape = new Triangle();
        // Here the shape reference variable referencing to Triangle object is allowed, however using this shape object. I cannot call
        shape.setTypeOfTriangle("Scalence")
        System.out.println("The shape of the triangle is " + shape.getTypeOfTriangle());
    }
}

My Question is if shape reference variable can be used to call only the getters and setters confined to what is defined in it, then why do we even consider using shape object to reference Triangle object. I have seen such code in few places but could not understand what is the advantange of doing it.

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
Divas
  • 455
  • 2
  • 7
  • 14
  • 1
    Closely related: https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface – Jon Skeet Sep 09 '19 at 09:33
  • 1
    As a standalone variable declaration maybe not so much but as a parameter to a method or to define the content of a collection it might be more useful – Joakim Danielson Sep 09 '19 at 09:37

1 Answers1

1

Why do we even consider using shape object to reference Triangle object?

To treat all Shapes equally and more abstractly.

Imagine there is a ShapeDrawer who doesn't care about specific properties a rectangular or triangle has. It just renders all shapes on its canvas assuming each shape knows how to draw itself.

abstract class Shape{
  abstract void draw();
}

class Triangle extends Shape{
  @Override
  void draw() {
    System.out.println("This is a drawing of the triangle.");
  }
}

class ShapeDrawer {
  public void drawAll(List<Shape> shapes) {
    shapes.forEach(Shape::draw);
  }
}

Imagine there is a ShapeNamePrinter who doesn't care what shapes look like. It just prints their names.

class ShapeNamePrinter {
  public void printShapeNames(List<Shape> shapes) {
    shapes.stream().map(Shape::getShapeName).forEach(System.out::println);
  }
}

To read:

What does it mean to "program to an interface"?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142