gpt4 book ai didi

java - Java 如何处理多个构造函数?

转载 作者:行者123 更新时间:2023-12-02 03:40:12 36 4
gpt4 key购买 nike

如果一个类包含两个接受不同类型参数的构造函数,如下所示:

public class Planet {
public double xxPos; //its current x position
public double yyPos; //its current y position
public double xxVel; //its current veolicity in the x direction
public double yyVel; //its current veolicity in the y direction
public double mass; //its mass
public String imgFileName; //The name of an image in the images directory that depicts the planet

// constructor is like __init__ from python, this sets up the object when called like: Planet(arguments)
public Planet(double xP, double yP, double xV, double yV, double m, String img) {
xxPos = xP;
yyPos = yP;
xxVel = xV;
yyVel = yV;
mass = m;
imgFileName = img;

}

// second constructor
// how come testplanetconstructor knows to use this second one?
// does it know based on the argument type its being passed?
public Planet(Planet p) {
xxPos = p.xxPos;
yyPos = p.yyPos;
xxVel = p.xxVel;
yyVel = p.yyVel;
mass = p.mass;
imgFileName = p.imgFileName;
}
}

我的主要问题是:1) 另一个具有调用该类的 main 的类如何确定使用哪个构造函数?

如果是这种情况,如果您有两个构造函数:2)相同类型和数量的参数?3)相同类型但不同数量的参数?

我意识到后续问题是你可能永远不应该做的事情(又名困惑的事情)。我只是好奇。

最佳答案

1) How does another class with a main that calls this class determine which constructor to use?

编译器通过检查唯一方法签名来遵循与静态绑定(bind)重载方法相同的过程。了解方法签名see this

public static void main(String args[]) {
double d1 = 0;
double d2 = 0;
double d3 = 0;
double d4 = 0;
double d5 = 0;
String img = "";
Planet p = new Planet(d1, d2, d3, d4, d5, img);// constructor with valid argument set
}

2) the same type and number of arguments?

实际上不可能在单个类中编写具有相同签名的两个方法/构造函数。例如以下代码永远不会编译

Planet(int i) {// compilation error
return 0;
}
Planet(int j) {// compilation error
return 0;
}

3) the same type but different number of arguments?

这是可能的,就像使用不同签名创建/调用方法一样。例如

Planet p1 = new Planet(d1, d2, d3, d4, d5, img);
Planet p2 = new Planet(p1);

关于java - Java 如何处理多个构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36911421/

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