Polymorphism in JAVA

 Polymorphism

• Polymorphism is one of three pillars of object-orientation.


• Polymorphism: many different (poly) forms of objects that

share a common interface respond differently when a method of that interface is invoked:

1) a super-class defines the common interface

2) sub-classes have to follow this interface (inheritance), but are also permitted to provide their own implementations (overriding)


• A sub-class provides a specialized behaviors relying on the

common elements defined by its super-class.

• A polymorphic reference can refer to different types of

objects at different times

– In java every reference can be polymorphic except of

references to base types and final classes.


• It is the type of the object being referenced, not the

reference type, that determines which method is invoked


– Polymorphic references are therefore resolved at run-

time, not during compilation; this is called dynamic binding


• Careful use of polymorphic references can lead to

elegant, robust software designs.


Method Overriding


• When a method of a sub-class has the same name and

type as a method of the super-class, we say that this

method is overridden.


• When an overridden method is called from within the

sub-class:

1) it will always refer to the sub-class method

2) super-class method is hidden


Example: Hiding with Overriding 1


class A {

int i, j;

A(int a, int b) {

i = a; j = b;

}

void show() {

System.out.println("i and j: " + i + " " + j);

}

}


Example: Hiding with Overriding 2


class B extends A {

int k;

B(int a, int b, int c) {

super(a, b);

k = c;

}

void show() {

System.out.println("k: " + k);

}

}


Example: Hiding with Overriding 3


• When show() is invoked on an object of type B, the version of show() defined in B is used:


class Override {

public static void main(String args[]) {

B subOb = new B(1, 2, 3);

subOb.show();

}

}


• The version of show() in A is hidden through overriding.

Post a Comment (0)
Previous Post Next Post