I have a Sport base class that has a couple variables. I also have a few different classes derived from Sport such as Volleyball, Soccer, etc. that have additional methods and variables. They look somewhat like this.
public class Sport {
public String commonVar;
public Sport(String c) {
this.commonVar = c;
}
}
And then Volleyball:
public class Volleyball extends Sport {
public String onlyVolleyball;
public Volleyball(String c, String thisVar) {
super(c);
this.onlyVolleyball = thisVar;
}
}
Now I want to be passing the derived classes of Sport into a function elsewhere, but making the parameters
public otherFunction(int one, int two, Sport sport) { }
Only treats sport as a Sport object (it will accept the derived classes but I cannot access any of the variables and methods not common to Sport). My question is how do I create a function that I am able to send all types of Sport derivatives to without losing any data?
You can’t, but you can check if the object is actually a member of the extending class, then cast it and use it, as follows: