Java Polymorphism

Java Polymorphism

  • Polymorphism is the third essential feature of an object-oriented programming language, after data abstraction and inheritance.
  • Poly means many, and morph means form: A polymorphic function is many-formed.
  • Building polymorphism is :
    • The capability to bind specific derived class objects to base class reference at runtime.
    • Create Overriding methods to change the behavior of objects in the sub-classes (it is called subtype polymorphism).
    A polymorphism example:
    class Vehicle {
    
      static int wheels = 4;
    
      public String Status() {
        return "I am a Vehicle with " + wheels + " wheels";
      }
    }
    
    class Trailer extends Vehicle {
    
      static int wheels = 16; // this hides statics wheels in Vehicle
    
      @Override   
      public String Status() {
        return "I am a Trailer with " + wheels + "  wheels";
      }
    }
    
    public class PolymorphismDemo {
    
      public static void main(String args[]) {
        Vehicle a = new Vehicle();      // Vehicle reference to an Vehicle object
        Vehicle b = new Trailer();      // Vehicle reference to a Trailer object
        System.out.println(a.Status()); // Runs the method in Vehicle class
        System.out.println(b.Status()); // Runs the method in Trailer class
      }
    }
    The result of this is:
    I am a Vehicle with 4 wheels
    I am a Trailer with 16  wheels
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.