gpt4 book ai didi

java - 创建接收多态输入的方法

转载 作者:行者123 更新时间:2023-12-01 13:10:30 27 4
gpt4 key购买 nike

我想调用一个名为“center”的特定方法,我用它来将对象的中心打印为字符串。我希望这个方法接受这些类中的任何对象。对象的中心是前两个 int 值 (x,y)。所有这些类都共享此方法,因为它是从 Circle2 类继承的。我在这个类的main方法中调用这个方法(即center()方法)。我打算创建的方法应该输出(替换 main 中的 println 方法)这些对象中心的值(我最终将其放置在 ArrayList 中,我必须检查其过程,因为我不能回想一下我会通过什么方式来解决这个问题)。对其中任何一个的任何见解都会非常有帮助。

简而言之,我的意思是在此类中创建一个方法,该方法将接受在此 main 中构造的任何对象(目前的情况)作为输入,然后输出调用 center() 方法的结果有共同点。

如果我的解释不完全清楚,我深表歉意 - 如果我的意思并不完全明显,我很乐意尝试进一步澄清该问题。

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

我引用的方法(center())如下:

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

最佳答案

你可以试试这个:

public interface Shape {

public String center();
}

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

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

像这样编辑你的方法:

public String showCenter(Shape shape) {
return shape.center();
}

关于java - 创建接收多态输入的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22903565/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com