英文:
Can a java class object be a state variable in another class?
问题
让我们假设我在Java中有一个Car类,然后我创建另一个名为ElectricCar的类。在我的ElectricCar类中,可以将Car对象作为状态变量吗?
英文:
Let's say I have a Car class in Java and then I make another class called ElectricCar. Can a Car object be a state variable in my ElectricCar class?
答案1
得分: 2
简而言之:是的。试试看:
class Car {
}
class ElectricCar {
Car myCar = new Car();
}
英文:
Simply put: yes. Try it:
class Car {
}
class ElectricCar {
Car myCar = new Car();
}
答案2
得分: 1
是的,这很常见:
class Car {
}
class ElectricCar {
private final Car car;
ElectricCar(Car car) {
this.car = car;
}
}
英文:
Yes; and it's quite common:
class Car {
}
class ElectricCar {
private final Car car;
ElectricCar(Car car) {
this.car = car;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论