object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementation. This is one of the basic principles of object oriented programming.
The method overriding is an example of runtime polymorphism. You can have a method in subclass overrides the method in its super classes with the same name and signature. Java virtual machine determines the proper method to call at the runtime, not at the compile time.
Let's take a look at the following example:
class veicle{
void whoAmI() {
System.out.println("I am a generic veicle.");
}
}
class carextends veicle{
void whoAmI() {
System.out.println("I am a car.");
}
}
class bus extends veicle{
void whoAmI() {
System.out.println("I am a bus.");
}
}
class RuntimePolymorphismDemo {
public static void main(String[] args) {
veicle ref1 = new veicle();
veicle ref2 = new car();
veicle ref3 = new bus();
ref1.whoAmI();
ref2.whoAmI();
ref3.whoAmI();
}
}
The output is
I am a generic veicle.
I am a car.
I am a bus.
The method overriding is an example of runtime polymorphism. You can have a method in subclass overrides the method in its super classes with the same name and signature. Java virtual machine determines the proper method to call at the runtime, not at the compile time.
Let's take a look at the following example:
class veicle{
void whoAmI() {
System.out.println("I am a generic veicle.");
}
}
class carextends veicle{
void whoAmI() {
System.out.println("I am a car.");
}
}
class bus extends veicle{
void whoAmI() {
System.out.println("I am a bus.");
}
}
class RuntimePolymorphismDemo {
public static void main(String[] args) {
veicle ref1 = new veicle();
veicle ref2 = new car();
veicle ref3 = new bus();
ref1.whoAmI();
ref2.whoAmI();
ref3.whoAmI();
}
}
The output is
I am a generic veicle.
I am a car.
I am a bus.
No comments:
Post a Comment