如何设置/获取名称 "ford" - 我在 class Vehicle 的主要方法中创建的 class Car 的实例?
How to set / get a name to "ford" - instance of class Car I have created in main method of class Vehicle?
如您所见,我卡在了应该为福特所有者设置名称的部分...感谢您的帮助。
public class Vehicle {
Person owner;
long motorSerialNo;
String registerNo;
public static void main(String[] args) {
//an example, create an object instance of class Car
Car ford = new Car();
ford.model = "Focus";
ford.motorSerialNo = 123456;
ford.registerNo = "CA-126-65";
//and here is a problem
ford.owner.setName("John Croul");
}
}
class Car extends Vehicle {
String model;
}
class Person {
public Person(String name){
this.name = name;
}
String name;
String lastname;
String address;
String getName() {
return name;
}
void setName() {
this.name = name;
}
}
首先,您的 setter 应该看起来像
public void setName(String name) {
this.name = name;
}
然后你必须在调用它的方法setName()
之前初始化实例变量person
,否则你会得到NullPoiterException
.
Person owner = new Person();
或在 main
方法中,就像您对其他变量所做的那样
ford.owner = new Person();
如您所见,我卡在了应该为福特所有者设置名称的部分...感谢您的帮助。
public class Vehicle {
Person owner;
long motorSerialNo;
String registerNo;
public static void main(String[] args) {
//an example, create an object instance of class Car
Car ford = new Car();
ford.model = "Focus";
ford.motorSerialNo = 123456;
ford.registerNo = "CA-126-65";
//and here is a problem
ford.owner.setName("John Croul");
}
}
class Car extends Vehicle {
String model;
}
class Person {
public Person(String name){
this.name = name;
}
String name;
String lastname;
String address;
String getName() {
return name;
}
void setName() {
this.name = name;
}
}
首先,您的 setter 应该看起来像
public void setName(String name) {
this.name = name;
}
然后你必须在调用它的方法setName()
之前初始化实例变量person
,否则你会得到NullPoiterException
.
Person owner = new Person();
或在 main
方法中,就像您对其他变量所做的那样
ford.owner = new Person();