Java OOP: how to use subclass object from superclass (this method has been overridden)
I have this example:
public class Inheritance {
public static class Animal {
public void Scream() {
System.out.println("I'm an animal");
}
}
public static class Mammal extends Animal{
public void Scream(){
System.out.println("I'm a mammal");
}
}
public static class Tiger extends Mammal{
public void Scream(){
System.out.println("I'm a tiger");
}
}
public static void main (String[] args){
Animal tiger = new Tiger();
tiger.Scream();
}
}
Of course I will get: "I am a tiger". But I don't know how to type "I am a mammal" or "I am an animal".
@: and please answer my question: in the case of a class Tiger
What is a superclass from Tiger
. Mammal
or Animal
?
Please help me:)
Thank::)
source to share
Here's some sample code:
public class Inheritance {
public static class Animal {
public void Scream() {
System.out.println("I'm an animal");
}
}
public static class Mammal extends Animal{
public void Scream(){
super.Scream();
System.out.println("I'm a mammal");
}
}
public static class Tiger extends Mammal{
public void Scream(){
super.Scream();
System.out.println("I'm a tiger");
}
}
public static void main (String[] args){
Animal tiger = new Tiger();
tiger.Scream();
}
}
source to share
To print "I am a mammal", you must make an object of the mammalian class.
public static void main (String[] args){
Animal mammal = new Mammal();
mammal.Scream();
}
To print "I am an animal", you must make an object of class Animal.
public static void main (String[] args){
Animal animal = new Animal();
animal.Scream();
}
NOTE. In both of these cases, the control variable remains Animal.
source to share
1) As the other guys already said, call super.Scream()
if you want to call overridden method from superclass. You will have the following output:
I'm an animal
I'm a mammal
I'm a tiger
2) Tiger implements Mammal, so Mammal is a superclass of Tiger, and since Animal is a superclass of Mammal, Tiger also implements Animal. In other words: the tiger's super heads are tiger and animal.
// all of this is valid:
Tiger tiger = new Tiger();
Mammal mammal = tiger;
Animal animal = tiger;
If you call animal.Scream()
, the virtual machine knows that it anmial
is of type Tiger and calls the yell method declared in the Tiger class. See Polymorphism .
source to share