Originally Posted by
turboman1
Are you talking about the Animal myAnimal = new Mammal() ? If so I thought that in this statement you are telling the compiler that myAnimal is of data type Mammal but it ONLY has access to the members of Animal class.
I'm not sure what you mean by "has access to" in this context. Since your myAnimal variable is of type Animal, yes, you'll only be able to call functions that exist in the Animal class. However, if you **override** one of those methods in the Mammal class, then the method from the Mammal class will be called.
Originally Posted by
turboman1
Animal myAnimal = new Mammal()
// Versus
Animal myAnimal = new Animal();
The differences between these two statements is...
The first statement declares myAnimal as data type Mammal, but it ONLY has access to Animal class members?
Again, "has access to" doesn't make a lot of sense to me in this context. The first statement declares myAnimal as type Animal, but it initializes it to a Mammal instance. You still "have access to" any methods in Mammal that **override** methods in Animal. The second statement declares the variable as the base type.
Let's expand the example. Let's say we have a base Animal class:
class Animal{
public void eat(){
System.out.println("The animal eats its food.");
}
public void talk(){
System.out.println("The animal talks.");
}
}
And we have two classes, Cat and Dog, that both extend it:
class Cat extends Animal{
public void eat(){
System.out.println("The CAT eats FISH.");
}
public void talk(){
System.out.println("The cat MEOWS.");
}
}
class Dog extends Animal{
public void eat(){
System.out.println("The DOG eats BONES.");
}
public void talk(){
System.out.println("The dog BARKS.");
}
}
Now, we can declare three Animal variables and initialize them to intances of each of the classes:
Animal animal = new Animal();
Animal cat = new Cat();
Animal dog = new Dog();
And we can create a function that takes an Animal as an argument and tells that animal to talk and eat:
public void talkAndEat(Animal a){
a.talk();
a.eat();
}
Now we can pass each instance (Animal, Cat, and Dog) into that function:
Animal animal = new Animal();
Animal cat = new Cat();
Animal dog = new Dog();
talkAndEat(animal);
talkAndEat(cat);
talkAndEat(dog);
What do you think that code would print out? I suggest writing a little example program to test your answer.