【发布时间】:2017-12-29 00:36:27
【问题描述】:
Java 新手 我正在研究如何使用对象和类。在下面的示例中,我尝试创建一个赛车比赛,其中一些车手可能已被其他一些车手跟踪/跟踪。特别是,我很难理解我是否正确使用了第二个构造函数。
public class CarDriver {
// Here I define some features of that class
private String name;
private int age;
// Here I create the first constructor
public CarDriver(String name, int age){
this.age = age;
this.name = name;
}
// Here I create the second constructor, where I try to use an instance of CarDriver to involve a tracker later on.
public CarDriver(String name, int age, CarDriver tracker){
tracker = new CarDriver(name,age);
this.name = name;
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
// Issues starting here. Since I dont know how to extract the information about the tracker
public getTracker(){
return tracker
}
// Basically I would need that information to figure out whether some drivers are beeing pursued by others.
public boolean hasPursuer(CarDriver driver)
{
if (driver.getTracker() == 0){
return true
} else {
return false
}
}
public static void main(String[] args) {
CarDriver driver1 = new CarDriver("Hamilton", 25);
CarDriver driver2 = new CarDriver("Schumacher", 23, driver1);
CarDriver driver3 = new CarDriver("Rosberg", 27, driver2);
CarDriver driver4 = new CarDriver("Susi", 27, driver3);
System.out.println(driver1.hasPursuer() + " " + driver2.hasPursuer());
}
}
【问题讨论】:
-
不,你没有正确使用它。您将立即覆盖作为
tracker传入的值,并且不对该覆盖的值执行任何操作。目前还不清楚你打算做什么。 -
你忘了写一个问题。这不是聊天。您还需要说明您要达到的目标以及问题出在哪里。
-
嗨@Palo 我很难理解我是否正确使用了第二个构造函数->我很难理解,是否正确使用了第二个构造函数?现在用问号更好吗?
-
没有。因为如果你不告诉我们你的意图是什么,没有人能恰当地理解你的意思。下面的 mckuok 试图猜测您想要什么,因此可能会有答案,但您需要更好地解释自己。
-
您应该稍微澄清一下您的问题。关于该对象可以拥有多少跟踪器/追赶者还不清楚。如果它可能有 One 或 None,你只需要一个 CarDriver 类型的成员变量来表示它,否则你将需要一个 List
.
标签: java constructor instance