gpt4 book ai didi

Java - getConstructor()?

转载 作者:搜寻专家 更新时间:2023-11-01 01:48:10 26 4
gpt4 key购买 nike

我把问题写成注释在代码里了,我觉得这样更容易理解。

public class Xpto{
protected AbstractClass x;

public void foo(){

// AbstractClass y = new ????? Car or Person ?????

/* here I need a new object of this.x's type (which could be Car or Person)
I know that with x.getClass() I get the x's Class (which will be Car or
Person), however Im wondering how can I get and USE it's contructor */

// ... more operations (which depend on y's type)
}

}

public abstract class AbstractClass {
}

public class Car extends AbstractClass{
}

public class Person extends AbstractClass{
}

有什么建议吗?

提前致谢!

最佳答案

首先,BalusC 是对的。

其次:

如果您根据类类型做出决定,您就不会让多态性发挥作用。

你的类结构可能是错误的(像 Car 和 Person 不应该在同一个层次结构中)

您可能会创建一个接口(interface)并为其编写代码。

interface Fooable {
Fooable createInstance();
void doFoo();
void doBar();
}

class Car implements Fooable {
public Fooable createInstance() {
return new Car();
}
public void doFoo(){
out.println("Brroooom, brooooom");
}
public void doBar() {
out.println("Schreeeeeeeekkkkkt");
}
}
class Person implements Fooable {
public Fooable createInstance(){
return new Person();
}
public void foo() {
out.println("ehem, good morning sir");
}
public void bar() {
out.println("Among the nations as among the individuals, the respect for the other rights means peace..");// sort of
}
}

稍后...

public class Xpto{
protected Fooable x;

public void foo(){
Fooable y = x.createInstance();
// no more operations that depend on y's type.
// let polymorphism take charge.
y.foo();
x.bar();
}
}

关于Java - getConstructor()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2702624/

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