Reputation: 1000
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();
Upvotes: 5
Views: 3031
Reputation: 77904
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).
Upvotes: 12
Reputation: 5055
I'd rather say they should behave as instances of the same class. The derived members should obey the general contract documented in the javadoc.
I would recommend you to read the wiki article and also take a look at the concepts of dynamic binding.
In short: the concrete invoked method depends on the runtime type of the referenced object not on the type of the referencing variable.
Upvotes: 0
Reputation: 718698
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.
Upvotes: 6
Reputation: 5429
Only a.g()
is polymorphism. As you have a reference of type A
but its calling the method in object B
.
Upvotes: 3