Question

I want to call a specific method named "center" which I use to print the centres of the objects as a string. I want this method to accept any object from these classes. The centres of the object are the first two int values (x,y). All of these classes share this method as it is inherited from the Circle2 class. I call this method (namely the center() method) in the main method of this class. The method I intend to create is supposed to output (replacing the println methods in the main) the values for centres of these objects (which I will eventually place within an ArrayList, whose process I'll have to review, as I can't recall by what means I would go about this). Any insight on either of these would be highly helpful.

In short--I mean to create a method in this class that will accept any of the objects constructed in this main (as they presently are) as input and then output the result of calling the center() method that they all have in common.

Apologies if my explanation isn't completely clear--if it isn't totally apparent what I mean to do, I would be happy to attempt to give further clarity on the issue.

public class TestPoly2
{
    /**
     * Constructor for objects of class TestPoly2
     */
    public TestPoly2()
    {

    }

    public String showCenter()
    {
        return "This method is supposed to output (replacing the println methods in the main) the values for centres of these objects (which I will eventually place within an ArrayList (whose process I'll have to review, as I can't recall by what means I would go about this) ";
    }

    public static void main(String []args)
    {
        Circle2 one =  new Circle2(5, 10, 4);
        Cylinder2 two = new Cylinder2(8, 7, 4, 12);
        Oval2 three =  new Oval2(3, 4, 9, 14);
        OvalCylinder2 four =  new OvalCylinder2(11, 14, 15, 10, 12);

        System.out.println(one.center());
        System.out.println(two.center());
        System.out.println(three.center());
        System.out.println(four.center());
    }
}

The method (center()) that I've been referencing is as follows:

public String center()
{
     return "center is at (" + x + "," + y + ")";
}
Was it helpful?

Solution 2

This is the proper method to perform the task.

    public static void showCenter(Circle2 object)
    {
        System.out.println(object.center());
    }

For anyone who is curious, of course. Thank you for the assistance, guys.

OTHER TIPS

u may try this:

public interface Shape {

    public String center();
}

public class Circle2 implements Shape {
    //ur rest of the code here...

    @Override
    public String center() {
      // return statement here.
    }
}

edit ur method like this:

public String showCenter(Shape shape) {
  return shape.center();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top