I am New to Java and OOPs Concepts, I am having trouble with this.
I have this function in the Train
Class (it associates the TrainCar
Class) in which I am running a for loop to loop through an array of Objects of type TrainCar
. TrainCar
is the parent class from which inherits the AdminCar
Class, which is further inherited by the TrainEngine
Class.
the TrainEngine
Class has a getter getPower, TrainCar
or AdminCar
does not have that.
when I want to access that method IntelliJ recommends me to change totalPower += car.getPower();
to totalPower += ((TrainEngine) car).getPower();
. I don't know what this line means and does. I would really appreciate it If you guys could explain this.
public double getMaxAccel() {
double totalPower = 0;
double totalWeight = 0;
for (TrainCar car: trainCar) {
totalWeight += car.getWeight();
if (car instanceof TrainEngine) {
totalPower += ((TrainEngine) car).getPower();
}
}
}
When you are trying to increase the totalPower, the line totalPower += ((TrainEngine) car).getPower();
is attempting to access the getPower method for each TrainCar object. However, the getPower method is only available in the TrainEngine class, not in the TrainCar class itself.
By using the type cast (TrainEngine) car, you are telling the compiler explicitly that you know the car object is of type TrainEngine. Therefore, it allows you to access the getPower() method without a compilation error.
Since you are new, I would advise you to study further into the Polymorphism and Inheritance concepts. I believe it will give you a good understanding of this problem.
I will give an example:
You have a class named Animal and two subclasses Cat and Dog. Let's say you have a bark()
method in the Dog class and meow()
method in the Cat class.
Say you want to create an instance of Dog from the parent class, Animal as follows:
Animal yourDog = new Dog();
Now you know that this object will be a dog but the computer doesn't. Hence, if you want to call the bark()
method of the subclass Dog, you need to tell the compiler that this object should be treated as a Dog.
So, you do this when calling the bark() method:
((Dog) animalDog).bark();
Hope this helps, good luck on your journey buddy! :)