Home > OS >  How to call a method from all implement java
How to call a method from all implement java

Time:11-20

I have one interface

public interface GeometricObject {
    public String getInfo();
}

And I have 2 classes, which implement the above interface.

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:

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

How can I call that method in all implements to that list

e.g.

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)]

CodePudding user response:

Just call it

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

CodePudding user response:

I you want more simplicity.
shapes.forEach(shape -> System.out.println(shape.getInfo()));

CodePudding user response:

First you have to add the fields that you need to your shapes. For example in the triangle you need p1, p2, p3. They must be part of the class if you want to get the right values printed.

E.g:

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