Why use type substitution [closed]

心不动则不痛 提交于 2019-12-12 02:41:32

问题


Can anyone explain to me what is the need of using type substitution?

e.g.

class Circle extends Shape{
   ...
}

.
.
.

class Main{
   public static void main(String[] args){
       Shape s = new Circle();
       ...
   }
}

What possible benifit can we get from the above code? Normally,

public static void main(String[] args){
    Circle c = new Circle();
}

would have done the required job easily.


回答1:


The phenomenon is called as polymorphism through inheritance. That means your behavior is decided at runtime on which object is being called instead of by which reference it is being called.

Well. lets extend your example further. Lets first create class hierarchy

class Shape{
      public void draw(){}
}

class Circle extends Shape{
      public void draw(){
          //mechanism to draw circle
      }
}

class Square extends Shape{
      public void draw(){
          //mechanism to draw square
      }
}

Now let's see how this can lead to clean code

class Canvas{
     public static void main(String[] args){
        List<Shape> shapes = new ArrayList<>();
        shapes.add(new Circle());
        shapes.add(new Square());

        // clean and neat code

        for(Shape shape : shapes){
              shape.draw();
        }

     }
 }

This can also help in making loose coupled system

 Class ShapeDrawer{
     private Shape shape;  

     public void setShape(Shape shape){
         this.shape = shape;
     }

     public void paint(){
         shape.draw(); 
     } 

 }

In this case, ShapeDrawer is very loosely coupled with actual shape. ShapeDrawer even doesn't know which type of Shape it is drawing or even mechanism of how it is drawing is abstracted from it. Underlying mechanism of drawing particular shape can be changed without affecting this class.



来源:https://stackoverflow.com/questions/25651066/why-use-type-substitution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!