0

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.

4

1 回答 1

3

这种现象被称为通过继承的多态性。这意味着您的行为是在运行时决定调用哪个对象而不是调用哪个引用。

出色地。让我们进一步扩展您的示例。让我们首先创建类层次结构

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
      }
}

现在让我们看看这如何导致干净的代码

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();
        }

     }
 }

这也有助于制作松耦合系统

 Class ShapeDrawer{
     private Shape shape;  

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

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

 }

在这种情况下,ShapeDrawer与实际形状非常松散耦合。ShapeDrawer甚至不知道Shape它正在绘制哪种类型,甚至不知道它是如何绘制的机制是 从中抽象出来的。可以改变绘制特定形状的底层机制而不影响这个类。

于 2014-09-03T18:26:04.413 回答