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?
Asked
Active
Viewed 107 times
-3
-
3Yes it can...... – ruohola May 29 '20 at 16:05
-
2Why shouldn't it? – Federico klez Culloca May 29 '20 at 16:07
-
It would work, because every `ElectricCar` is a `Car`, but not every `Car` has to be an `ElectricCar`. – Nosrep May 29 '20 at 17:00
2 Answers
2
Simply put: yes. Try it:
class Car {
}
class ElectricCar {
Car myCar = new Car();
}

David Conrad
- 15,432
- 2
- 42
- 54

Daniel H.
- 301
- 2
- 13
-
-
-
if I instantiate an ElectricCar object in "main" and want to access the attributes/state variables of the Car object, how would I do this? if my ElectricCar object name is electricOne, and let's say there is a Car state variable called engineSize that has a default value of 350. How can I get this value using the ElectricCar instance? Thanks! – Tad May 29 '20 at 16:42
-
@Tad you should be able to, from the main class, access this like so: electricOne.myCar.engineSize – Daniel H. May 29 '20 at 16:43
-
actually just got it. needed to make my Car state variables public rather than private. But is that right? Under my question, I would access the engineSize by calling electricOne.myCar.engineSize. But shouldn't I be able to keep engineSize private in the Car class and still be able to access it using electricOne.myCar.engineSize? – Tad May 29 '20 at 16:46
-
private in java means only its parent class or inheriting classes can access it. So, engineSize would need to be public (or package-private if you are using a package) – Daniel H. May 29 '20 at 16:49
-
Many thanks! I've been working Python for too long and just got away from Java. If you don't use it you lose it! – Tad May 29 '20 at 16:53
-
no problem! If your question is answered fully, would you mind accepting the answer? – Daniel H. May 29 '20 at 16:56
1
Yes; and it's quite common:
class Car {
}
class ElectricCar {
private final Car car;
ElectricCar(Car car) {
this.car = car;
}
}

Jan Nielsen
- 10,892
- 14
- 65
- 119