Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these examples of polymorphism?

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();
like image 842
Bin Avatar asked Sep 10 '13 07:09

Bin


3 Answers

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.

enter image description here

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).

like image 109
Maxim Shoustin Avatar answered Nov 15 '22 05:11

Maxim Shoustin


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.

like image 44
Stephen C Avatar answered Nov 15 '22 05:11

Stephen C


Only a.g() is polymorphism. As you have a reference of type A but its calling the method in object B.

like image 22
Ean V Avatar answered Nov 15 '22 05:11

Ean V