I'm working through a Java polymorphism exercise and struggling to understand type conversion & how to call subclass-specific methods. I have a class Dog:
public class Dog { private final String breed; public Dog(String b) { breed = b; } //More Dog methods (bark, eat, etc.) } as well as a subclass SledDog, who can pull a sled:
public class SledDog extends Dog { public SledDog(String b) { super(b); } public void pullSled() { System.out.println("pulling the sled"); } } In my application, I declare 3 dogs - two regular Dogs and one SledDog. I pass them into an array of Dogs, and I loop through that array. If the dog is a sled dog, I want him to pullSled() - but I can't figure out how to call the method, since it belongs to a subclass. My instructions tell me to cast the array item into a SledDog object, but I can't figure out how, or why it is necessary. I thought that since the object passed to array is already a SledDog, it should have access to pullSled(). Here's my attempt.
public class DogApp { public static void main(String[] args) { Dog firstDog = new Dog("Greyhound"); Dog secondDog = new Dog("Terrier"); SledDog sledDog = new SledDog("Husky"); Dog[] dogArray = new Dog[]{firstDog, secondDog, sledDog}; for(Dog d : dogArray) { //Makes sense, only want to pullSled() if d is a SledDog if(d instanceof SledDog) { // This is the part I'm confused about d = (SledDog) d; d.pullSled(); } } } }