ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

Polymorphism in Java

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic.

In polymorphism, two things internally process:

  1. Method Overriding
  2. Auto upcasting

Together both brings polymorphism. Inheritance is used for polymorphism.

Let’s take one example

  1. class A{
  2.  
  3. void test(){
  4.  
  5. System.out.println("A-test");
  6.  
  7. }
  8.  
  9. }
  10.  
  11. class B extends A{
  12.  
  13. void test(){  //method overriding
  14.  
  15. System.out.println("B-test");
  16.  
  17. }
  18.  
  19. }
  20.  
  21. class Manager(){
  22.  
  23. public static void main(String[] ar) {
  24.  
  25. A a1=new A();
  26.  
  27. A a2=new B(); //upcasting
  28.  
  29. a1.test();
  30.  
  31. a2.test();
  32.  
  33. }
  34.  
  35. }
  36.  
  37. Output:
  38.  
  39. A-test
  40.  
  41. B-Test

 

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!