gpt4 book ai didi

Java - 将对象传递给扩展类

转载 作者:行者123 更新时间:2023-12-01 18:35:45 26 4
gpt4 key购买 nike

假设我有两个公共(public)类(class),如下所示:

椭圆形类将获取宽度和高度参数。

public class Oval extends Shape{
OvalClass oval;
public Oval(int width,int height){
oval = new OvalClass("first",10);
}

}

还有一个 Shape 类,它应该具有任何不同的形式(这就是我扩展它的原因)。

public class Shape {

public void moveLeft(){
//object?
object.posX += 1;
}
}

编辑:

We don't know enough about GOval, the other classes, and the move() method to give a good answer.

将另一个 OvalClass 视为椭圆形类:

public class OvalClass {
String name;
int posX;
public OvalClass(String name, int posx){}
}

问题是,如何获得在 Shape 类的 Oval 中创建的 object 椭圆形 (GOval oval)?有没有更好的方法?

最佳答案

尝试这样的事情:

public class Shape {
// Now all Shapes can move()
protected abstract void move(int x, int y);
public void moveLeft(){
//object?
move(-1,0);
}
}

public class Oval extends Shape {
private GOval oval;
public Oval(int width,int height) {
oval = new GOval(0,0,width,height);
}
// Implement move()
protected void move(int x, int y) {
oval.move(x, y);// or whatever method on GOval makes it move()
}
}

HTH

关于Java - 将对象传递给扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22103833/

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