简体   繁体   English

如何从所有实现中调用方法 java

[英]How to call a method from all implement java

I have one interface我只有一个界面

public interface GeometricObject {
    public String getInfo();
}

And I have 2 classes, which implement the above interface.我有 2 个类,它们实现了上述接口。

public class Circle implements GeometricObject {
   @Override
   public String getInfo() {
      return "Circle[center,radius]";
   }
}

public class Triangle implements GeometricObject {
   @Override
   public String getInfo() {
      return "Triangle[p1,p2,p3]";
   }
}

And now I have this class to show all info that:现在我有这个 class 来显示所有信息:

public class shapeUtils{
   public String printInfo(List<GeometricObject> shapes) {
      //code here
   }
}

How can I call that method in all implements to that list如何在该列表的所有实现中调用该方法

eg例如

Circle:
Circle[(1,2),r=3]
Circle[(5,6),r=2]
Triangle:
Triangle[(1,2),(2,3),(3,0)]
Triangle[(-1,-3),(-5,3),(0,0)]

Just call it就叫吧

for (GeometricObject  shp : shapes) {
    System.out.println (shp.getInfo());
}

I you want more simplicity.我想要更简单。
shapes.forEach(shape -> System.out.println(shape.getInfo()));

First you have to add the fields that you need to your shapes.首先,您必须将所需的字段添加到您的形状中。 For example in the triangle you need p1, p2, p3.例如,在三角形中,您需要 p1、p2、p3。 They must be part of the class if you want to get the right values printed.如果要打印正确的值,它们必须是 class 的一部分。

Eg:例如:

public class Circle implements GeometricObject {
  
   private double center;
   private double radius;

   @Override
   public String getInfo() {
      return "Circle[ " + this.center + ", " + this.radius + " ]";
   }
   // Getters and setters
}

You do the same for all the shapes.你对所有的形状都做同样的事情。

You can fill a list with objects like this:您可以使用以下对象填充列表:

java.util.List<GeometricObject> shapes = new ArrayList<>();

Circle circle = new Circle(); // Initialize it

circle.setCenter(2); // Set the values
circle.setRadius(2);

shapes.add(circle); // Add it to the list

// Add some more objects into the list...


// Print them:

for (GeometricObject  shape : shapes) {
    System.out.println(shape.getInfo());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM