Search Google

Saturday 4 October 2014

LEARN JAVA Runtime Polymorphism



/**
 * Pyramid - Nested For Loop Example
 *
 * This example shows how to generate a pyramid like the one shown below using
 * simple Java for loop
 *
 *     *****
 *      ****
 *      ***
 *      **
 *      *
 *      *
 *      **
 *      ***
 *      ****
 *      *****
 *
 *
 *
 */
public class PyramidNestedForLoopExample_4 {

    public static void main(String[] args) {

        // generate first-half of the pyramid
        for(int i=5; i>0 ;i--){

            for(int j=0; j < i; j++){
                // display/add star
                System.out.print("*");
            }

            //create a new line
            System.out.println("");
        }// end of for loop

        // generate second-half of the pyramid
        for(int i=1; i<= 5 ;i++){

            for(int j=0; j < i; j++){
                // display/add star
                System.out.print("*");
            }

            //create a new line
            System.out.println("");
        }// end of for loop

    }

}


=====================================
// generate first-half of the pyramid
        for(int i=5; i>=1;i--){

            for(int j=1; j <= i; j++){
                // display/add star
                System.out.print(j);
            }
            System.out.println("");
        }
     -------------------------------------------------------------


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
Upcasting in java
  1. class A{}  
  2. class B extends A{}  
  1. A a=new B();//upcasting  

Example of Runtime Polymorphism

In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
  1. class Bike{  
  2.   void run(){System.out.println("running");}  
  3. }  
  4. class Splender extends Bike{  
  5.   void run(){System.out.println("running safely with 60km");}  
  6.   
  7.   public static void main(String args[]){  
  8.     Bike b = new Splender();//upcasting  
  9.     b.run();  
  10.   }  
  11. }  
Test it Now
Output:running safely with 60km.

Real example of Java Runtime Polymorphism

Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.
Java Runtime Polymorphism example of bank Note: It is also given in method overriding but there was no upcasting.
  1. class Bank{  
  2. int getRateOfInterest(){return 0;}  
  3. }  
  4.   
  5. class SBI extends Bank{  
  6. int getRateOfInterest(){return 8;}  
  7. }  
  8.   
  9. class ICICI extends Bank{  
  10. int getRateOfInterest(){return 7;}  
  11. }  
  12. class AXIS extends Bank{  
  13. int getRateOfInterest(){return 9;}  
  14. }  
  15.   
  16. class Test3{  
  17. public static void main(String args[]){  
  18. Bank b1=new SBI();  
  19. Bank b2=new ICICI();  
  20. Bank b3=new AXIS();  
  21. System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());  
  22. System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());  
  23. System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());  
  24. }  
  25. }  
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Runtime Polymorphism with data member

Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data members.
In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.

  1. class Bike{  
  2.  int speedlimit=90;  
  3. }  
  4. class Honda3 extends Bike{  
  5.  int speedlimit=150;  
  6.   
  7.  public static void main(String args[]){  
  8.   Bike obj=new Honda3();  
  9.   System.out.println(obj.speedlimit);//90  
  10. }  
Test it Now
Output:90

Runtime Polymorphism with Multilevel Inheritance

Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
  1. class Animal{  
  2. void eat(){System.out.println("eating");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6. void eat(){System.out.println("eating fruits");}  
  7. }  
  8.   
  9. class BabyDog extends Dog{  
  10. void eat(){System.out.println("drinking milk");}  
  11.   
  12. public static void main(String args[]){  
  13. Animal a1,a2,a3;  
  14. a1=new Animal();  
  15. a2=new Dog();  
  16. a3=new BabyDog();  
  17.   
  18. a1.eat();  
  19. a2.eat();  
  20. a3.eat();  
  21. }  
  22. }  
Test it Now
Output: eating
        eating fruits
        drinking Milk

Try for Output

  1. class Animal{  
  2. void eat(){System.out.println("animal is eating...");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6. void eat(){System.out.println("dog is eating...");}  
  7. }  
  8.   
  9. class BabyDog1 extends Dog{  
  10. public static void main(String args[]){  
  11. Animal a=new BabyDog1();  
  12. a.eat();  
  13. }}  
Test it Now
Output: Dog is eating

 --------------------------------------------------------------------------------------------------------

Static Binding and Dynamic Binding

static binding and dynamic binding in java Connecting a method call to the method body is known as binding.
There are two types of binding
  1. static binding (also known as early binding).
  2. dynamic binding (also known as late binding).

Understanding Type

Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.
  1. int data=30;  
Here data variable is a type of int.

2) References have a type

  1. class Dog{  
  2.  public static void main(String args[]){  
  3.   Dog d1;//Here d1 is a type of Dog  
  4.  }  
  5. }  

3) Objects have a type

An object is an instance of particular java class,but it is also an instance of its superclass.
  1. class Animal{}  
  2.   
  3. class Dog extends Animal{  
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.  }  
  7. }  
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding

When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.

Example of static binding

  1. class Dog{  
  2.  private void eat(){System.out.println("dog is eating...");}  
  3.   
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.   d1.eat();  
  7.  }  
  8. }  

Dynamic binding

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

  1. class Animal{  
  2.  void eat(){System.out.println("animal is eating...");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6.  void eat(){System.out.println("dog is eating...");}  
  7.   
  8.  public static void main(String args[]){  
  9.   Animal a=new Dog();  
  10.   a.eat();  
  11.  }  
  12. }  
Test it Now
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.




---------------------------------------
-----------------------------------------
------------------------------------------

An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.
  • It is used to achieve fully abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface method and public, static and final keywords before data members.

In other words, Interface fields are public, static and final bydefault, and methods are public and abstract.
interface

Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface.
relationship between class and interface

Simple example of Java interface

In this example, Printable interface have only one method, its implementation is provided in the A class.
  1. interface printable{  
  2. void print();  
  3. }  
  4.   
  5. class A6 implements printable{  
  6. public void print(){System.out.println("Hello");}  
  7.   
  8. public static void main(String args[]){  
  9. A6 obj = new A6();  
  10. obj.print();  
  11.  }  
  12. }  
Test it Now
Output:Hello

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.
 multiple inheritance in java
  1. interface Printable{  
  2. void print();  
  3. }  
  4.   
  5. interface Showable{  
  6. void show();  
  7. }  
  8.   
  9. class A7 implements Printable,Showable{  
  10.   
  11. public void print(){System.out.println("Hello");}  
  12. public void show(){System.out.println("Welcome");}  
  13.   
  14. public static void main(String args[]){  
  15. A7 obj = new A7();  
  16. obj.print();  
  17. obj.show();  
  18.  }  
  19. }  
Test it Now
Output:Hello
       Welcome

Q) Multiple inheritance is not supported through class in java but it is possible by interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class. For example:
  1. interface Printable{  
  2. void print();  
  3. }  
  4.   
  5. interface Showable{  
  6. void print();  
  7. }  
  8.   
  9. class testinterface1 implements Printable,Showable{  
  10.   
  11. public void print(){System.out.println("Hello");}  
  12.   
  13. public static void main(String args[]){  
  14. testinterface1 obj = new testinterface1();  
  15. obj.print();  
  16.  }  
  17. }  
Test it Now
Hello
As you can see in the above example, Printable and Showable interface have same methods but its implementation is provided by class A, so there is no ambiguity.

Interface inheritance

A class implements interface but one interface extends another interface .
  1. interface Printable{  
  2. void print();  
  3. }  
  4. interface Showable extends Printable{  
  5. void show();  
  6. }  
  7. class Testinterface2 implements Showable{  
  8.   
  9. public void print(){System.out.println("Hello");}  
  10. public void show(){System.out.println("Welcome");}  
  11.   
  12. public static void main(String args[]){  
  13. Testinterface2 obj = new Testinterface2();  
  14. obj.print();  
  15. obj.show();  
  16.  }  
  17. }  
Test it Now
       Hello
       Welcome

Q) What is marker or tagged interface?

An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.
  1. //How Serializable interface is written?  
  2. public interface Serializable{  
  3. }  

Nested Interface in Java

Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the nested classes chapter. For example:
  1. interface printable{  
  2.  void print();  
  3.  interface MessagePrintable{  
  4.    void msg();  
  5.  }  
  6. }  
More about Nested Interface--------------------------------------
-----------------------------------------------------------






----------------------------------------------------

Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstaction

There are two ways to achieve abstraction in java
  1. Abstract class (0 to 100%)
  2. Interface (100%)

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Example abstract class

  1. abstract class A{}  

abstract method

A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method

  1. abstract void printStatus();//no body and abstract  

Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.
  1. abstract class Bike{  
  2.   abstract void run();  
  3. }  
  4.   
  5. class Honda4 extends Bike{  
  6. void run(){System.out.println("running safely..");}  
  7.   
  8. public static void main(String args[]){  
  9.  Bike obj = new Honda4();  
  10.  obj.run();  
  11. }  
  12. }  
Test it Now
running safely..

Understanding the real scenario of abstract class

In this example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end user) and object of the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class. We will learn about the factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked.
File: TestAbstraction1.java
  1. abstract class Shape{  
  2. abstract void draw();  
  3. }  
  4. //In real scenario, implementation is provided by others i.e. unknown by end user  
  5. class Rectangle extends Shape{  
  6. void draw(){System.out.println("drawing rectangle");}  
  7. }  
  8.   
  9. class Circle1 extends Shape{  
  10. void draw(){System.out.println("drawing circle");}  
  11. }  
  12.   
  13. //In real scenario, method is called by programmer or user  
  14. class TestAbstraction1{  
  15. public static void main(String args[]){  
  16. Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method  
  17. s.draw();  
  18. }  
  19. }  
Test it Now
drawing circle

Another example of abstract class in java

File: TestBank.java
  1.  abstract class Bank{    
  2. abstract int getRateOfInterest();    
  3. }    
  4.     
  5. class SBI extends Bank{    
  6. int getRateOfInterest(){return 7;}    
  7. }    
  8. class PNB extends Bank{    
  9. int getRateOfInterest(){return 7;}    
  10. }    
  11.     
  12. class TestBank{    
  13. public static void main(String args[]){    
  14. Bank b=new SBI();//if object is PNB, method of PNB will be invoked    
  15. int interest=b.getRateOfInterest();    
  16. System.out.println("Rate of Interest is: "+interest+" %");    
  17. }}    
Test it Now
Rate of Interest is: 7 %

Abstract class having constructor, data member, methods etc.

An abstract class can have data member, abstract method, method body, constructor and even main() method.
File: TestAbstraction2.java
  1. //example of abstract class that have method body  
  2.  abstract class Bike{  
  3.    Bike(){System.out.println("bike is created");}  
  4.    abstract void run();  
  5.    void changeGear(){System.out.println("gear changed");}  
  6.  }  
  7.   
  8.  class Honda extends Bike{  
  9.  void run(){System.out.println("running safely..");}  
  10.  }  
  11.  class TestAbstraction2{  
  12.  public static void main(String args[]){  
  13.   Bike obj = new Honda();  
  14.   obj.run();  
  15.   obj.changeGear();  
  16.  }  
  17. }  
Test it Now
       bike is created
       running safely..
       gear changed

Rule: If there is any abstract method in a class, that class must be abstract.

  1. class Bike12{  
  2. abstract void run();  
  3. }  
Test it Now
compile time error

Rule: If you are extending any abstract class that have abstract method, you must either provide the implementation of the method or make this class abstract.


Another real scenario of abstract class

The abstract class can also be used to provide some implementation of the interface. In such case, the end user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.

  1. interface A{  
  2. void a();  
  3. void b();  
  4. void c();  
  5. void d();  
  6. }  
  7.   
  8. abstract class B implements A{  
  9. public void c(){System.out.println("I am C");}  
  10. }  
  11.   
  12. class M extends B{  
  13. public void a(){System.out.println("I am a");}  
  14. public void b(){System.out.println("I am b");}  
  15. public void d(){System.out.println("I am d");}  
  16. }  
  17.   
  18. class Test5{  
  19. public static void main(String args[]){  
  20. A a=new M();  
  21. a.a();  
  22. a.b();  
  23. a.c();  
  24. a.d();  
  25. }}  
Test it Now
Output:I am a
       I am b
       I am c
       I am d



No comments:

Post a Comment