Reputation: 33
I have a super class that defines some sub classes. I have another class that has a method which will be passed an object parameter that extends the super class. If the object's type is set to the super class, can you still pass the sub classes to the method? Sorry if it doesn't make sense. I can add some code as an example. Thanks in advance
EDIT:
public class Unit {
some code.
}
public class Infantry extends Unit {
some code.
}
public class DamageCalculator {
public double calculateDamage(Unit unit, double damage) {
Some code.
}
If I pass an object of type Infantry, will the compiler throw an error that the infantry object is not of type unit?
Upvotes: 0
Views: 60
Reputation: 13560
Your example will compile just fine. Since an instance of Infantry is a type of Unit you can pass it to the method calculateDamage. The complier will be happy with this. Any methods calculateDamage calls on unit will call the appropriate method on Unit or on Infantry if the have been overridden in the sub class. This is called "runtime polymorphism".
public class Unit { }
public class Infantry extends Unit { }
public class DamageCalculator {
public double calculateDamage(Unit unit, double damage) {
return damage; // presumably return unit.getStrength() * damage;
}
}
public class Main {
public static void main(String [] a) {
Unit i = new Infantry();
DamageCalculator damageCalculator = new DamageCalculator();
double damage = 0.1;
double result = damageCalculator.calculateDamage(i, damage);
}
}
Upvotes: 2