After browsing some questions about polymorphism, it seems that polymorphism is a general idea in Java that allows an object to behave as if it were an instance of another class; thus code is more independent from the concrete class. Given this idea, are the two method calls in the following main()
method usages of polymorphism?
abstract class A
{
void f() { System.out.println("A.f()"); }
abstract void g();
}
class B extends A
{
void g() { System.out.println("B.g()"); }
}
public class Test
{
public static void main(String[] args)
{
A a = new B();
a.f(); // Is this an example of Polymorphism?
a.g(); // ...
}
}
The output is:
A.f();
B.g();
Polymorphism – means the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references. In a nutshell, polymorphism is a bottom-up method call. The benefit of polymorphism is that it is very easy to add new classes of derived objects without breaking the calling code (i.e. getTotArea() in the sample code shown below) that uses the polymorphic classes or interfaces. When you send a message to an object even though you don’t know what specific type it is, and the right thing happens, that’s called polymorphism. The process used by object-oriented programming languages to implement polymorphism is called dynamic binding.
it seems that Polymorphism is a general idea in Java
Polymorphism, inheritance and encapsulation are the 3 pillar of an object-oriented language(Not Java only).
Both are examples of polymorphism. The B
is behaving like an A
. (I previously missed the abstract void g()
declaration. Or did you add it while we were answering??)
However, in this case "an A
" is a bit rubbery. Since A
is abstract
you can't have an object that is an A
and not an instance of some other class.
Only a.g()
is polymorphism. As you have a reference of type A
but its calling the method in object B
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With