Sunteți pe pagina 1din 17

OOP Lab

Instructor: M Ahmad Nawaz

ahma.fust@gmail.com

Java Polymorphism in OOP’s with Example


We have one parent class, ‘Account’ with function of deposit and withdraw. Account
has 2 child classes

The operation of saving and withdraw is same for Saving and Checking accounts. So
the inherited methods from Account class will work.

Change in Software Requirement

There is a change in the requirement specification, something that is so common in the


software industry. You are supposed to add functionality privileged Banking Account
with Overdraft Facility.

For a background, overdraft is a facility where you can withdraw an amount more than
available the balance in your account.
So, withdraw method for privileged needs to implemented afresh. But you do not
change the tested piece of code in Savings and Checking account. This is advantage of
OOPS

Step 1) Such that when the "withdrawn" method for saving account is called a method
from parent account class is executed.
Step 2) But when the "Withdraw" method for the privileged account (overdraft
facility) is called withdraw method defined in the privileged class is executed. This
is Polymorphism.
Method Overriding
Method Overriding is redefining a super class method in a sub class.

Rules for Method Overriding

 The method signature i.e. method name, parameter list and return type have to
match exactly.
 The overridden method can widen the accessibility but not narrow it, i.e. if it is
private in the base class, the child class can make it public but not vice versa.

Example

class Doctor{
public void treatPatient(){
// treatPatient method

}
class Surgeon extends Doctor{
public void treatPatient(){
// treatPatient method
}
}
Class run{
public static void main (String args[]){
Doctor doctorObj = new Doctor()
// treatPatient method in class Doctor will be executed
doctorObj.treatPatient();

Surgeon surgeonObj = new Surgeon();


// treatPatient method in class Surgeon will be executed
surgeonObj.treatPatient();
}
}

Difference between Overloading and Overriding


Method Overloading Method Overriding
Method overriding is when one of the methods
Method overloading is in the same class,
in the super class is redefined in the sub-class.
where more than one method have the
In this case, the signature of the method
same name but different signatures.
remains the same.
Ex:

class X{
public int sum(){
// some code
Ex:
}
}
void sum (int a , int b);
void sum (int a , int b, int c);
class Y extends X{
void sum (float a, double b);
public int sum(){
//overridden method
//signature is same
}
}

What is Dynamic Polymorphism?


Dynamic Polymorphism is the mechanism by which multiple methods can be defined
with same name and signature in the superclass and subclass. The call to an overridden
method are resolved at run time.
Dynamic Polymorphism Example:
A reference variable of the super class can refer to a sub class object

Doctor obj = new Surgeon();

Consider the statement

obj.treatPatient();

Here the reference variable "obj" is of the parent class, but the object it is pointing to is
of the child class (as shown in the diagram).

obj.treatPatient() will execute treatPatient() method of the sub-class - Surgeon

If a base class reference is used to call a method, the method to be invoked is decided
by the JVM, depending on the object the reference is pointing to

For example, even though obj is a reference to Doctor, it calls the method of Surgeon,
as it points to a Surgeon object

This is decided during run-time and hence termed dynamic or run-time polymorphism
Polymorphism can be achieved in two of the following ways:
 Method Overloading(Compile time Polymorphism)
 Method Overriding(Run time Polymorphism)

 Static Polymorphism is in other words termed as compile-time binding or early binding.


 Static binding occurs at compile time. Method overloading is a case of static binding and in this
case binding of method call to its definition happens at the time of compilation.

Method Overloading
 To call an overloaded method in Java, it is must use the type and/or the number of arguments to
determine which version of the overloaded method actually to call.
 The overloaded methods may have varied return types and the return type single-handedly is
insufficient to make out two versions of a method.
 As and when Java compiler encounters a call to an overloaded method, it simply executes the
version of the method whose parameters match the arguments used in the call.
 It permits the user to obtain compile time polymorphism with name method name.
 An overloaded method can throw different kinds of exceptions.
 A method which is overloaded can contain different access modifiers.

Overloading method's argument lists might differ in:

 Number of parameters passed


 Data type of actual parameters
 Sequence of data type of actual parameters

Program for Method Overloading in Java


Example:
class Mltply {

void mul(int a, int b) {

System.out.println("Sum of two=" + (a * b));

}
void mul(int a, int b, int c) {

System.out.println("Sum of three=" + (a * b * c));

class Polymorphism {

public static void main(String args[]) {

Mltply m = new Mltply();

m.mul(6, 10);

m.mul(10, 6, 5);

Method Overriding

Rules of method overriding in Java


 Argument list: The argument list at the time of overriding method need to be same as that of the
method of the parent class. The data types of the arguments along with their sequence must have
to be preserved as it is in the overriding method.
 Access Modifier: The Access Modifier present in the overriding method (method of subclass)
cannot be more restrictive than that of an overridden method of the parent class.
 The private, static and final methods can't be overridden as they are local to the class.
 Any method which is overriding can throw any unchecked exceptions, in spite of whether the
overridden method usually method of parent class might throw an exception or not.

Program for Method Overriding in Java


Example:
class parent {

public void work() {


System.out.println("Parent is under retirement from work.");

class child extends parent {

public void work() {

System.out.println("Child has a job");

System.out.println(" He is doing it well");

public static void main(String argu[]) {

child c1 = new child();

c1.work();

Advantage of method overriding


One significant advantage of method overriding is that a class can give its specific execution to an
inherited method without having the modification in the parent class (base class)

Super Keyword
What if the treatPatient method in the Surgeon class wants to execute the functionality
defined in Doctor class and then perform its own specific functionality?

In this case, keyword supercan be used to access methods of the parent class from the
child class.

The treatPatient method in the Surgeon class could be written as:


treatPatient(){
super.treatPatient();
//add code specific to Surgeon
}

The keyword super can be used to access any data member or methods of the super
class in the sub class.
Example:-To learn Inheritance, Polymorphism & super keyword

Step 1) Copy the following code into an Editor

public class Test{


public static void main(String args[]){
X x= new X();
Y y = new Y();
y.m2();
//x.m1();
//y.m1();
//x = y;// parent pointing to object of child
//x.m1() ;
//y.a=10;
}

}
class X{
private int a;
int b;
public void m1(){
System.out.println("This is method m1 of class X");
}
}

class Y extends X{
int c; // new instance variable of class Y
public void m1(){
// overriden method
System.out.println("This is method m1 of class Y");
}
public void m2(){
super.m1();
System.out.println("This is method m2 of class Y");
}
}
Step 2) Save, Compile & Run the code. Observe the output.

Step 3) Uncomments lines # 6-9. Save, Compile & Run the code. Observe the output.

Step 4) Uncomment line # 10 . Save & Compile the code.

Step 5) Error = ? This is because sub-class cannot access private members of the super
class.

Difference between Static & Dynamic Polymorphism


Static Polymorphism Dynamic Polymorphism
It relates to method overloading. It relates to method overriding.
Errors, if any, are resolved at compile time. In case a reference variable is calling an overridden me
Since the code is not executed during method to be invoked is determined by the object, your
compilation, hence the name static. variable is pointing to. This is can be only determined a
code in under execution, hence the name dynamic.
Ex:
Ex:
void sum (int a , int b);
void sum (float a, double b); //reference of parent pointing to child object
int sum (int a, int b); //compiler gives error. Doctor obj = new Surgeon();
// method of child called
obj.treatPatient()
Java Runtime (Dynamic) Polymorphism Example: Animal
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }
7. class Cat extends Animal{
8. void eat(){System.out.println("eating rat...");}
9. }
10. class Lion extends Animal{
11. void eat(){System.out.println("eating meat...");}
12. }
13. class TestPolymorphism3{
14. public static void main(String[] args){
15. Animal a;
16. a=new Dog();
17. a.eat();
18. a=new Cat();
19. a.eat();
20. a=new Lion();
21. a.eat();
22. }}

Java Runtime Polymorphism Example: Shape


1. class Shape{
2. void draw(){System.out.println("drawing...");}
3. }
4. class Rectangle extends Shape{
5. void draw(){System.out.println("drawing rectangle...");}
6. }
7. class Circle extends Shape{
8. void draw(){System.out.println("drawing circle...");}
9. }
10. class Triangle extends Shape{
11. void draw(){System.out.println("drawing triangle...");}
12. }
13. class TestPolymorphism2{
14. public static void main(String args[]){
15. Shape s;
16. s=new Rectangle();
17. s.draw();
18. s=new Circle();
19. s.draw();
20. s=new Triangle();
21. s.draw();
22. }
23. }

Java 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. class Dog extends Animal{
5. void eat(){System.out.println("eating fruits");}
6. }
7. class BabyDog extends Dog{
8. void eat(){System.out.println("drinking milk");}
9. public static void main(String args[]){
10. Animal a1,a2,a3;
11. a1=new Animal();
12. a2=new Dog();
13. a3=new BabyDog();
14. a1.eat();
15. a2.eat();
16. a3.eat();
17. }
18. }

Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}

Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}

class MyMainClass {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

Example

public class PolymorphismChallenge {


static abstract class Simpson {
void talk() {
System.out.println("Simpson!");
}
protected void prank(String prank) {
System.out.println(prank);
}
}
static class Bart extends Simpson {
String prank;
Bart(String prank) { this.prank = prank; }
protected void talk() {
System.out.println("Eat my shorts!");
}
protected void prank() {
super.prank(prank);
System.out.println("Knock Homer down");
}
}
static class Lisa extends Simpson {
void talk(String toMe) {
System.out.println("I love Sax!");
}
}
public static void main(String... doYourBest) {
new Lisa().talk("Sax :)");
Simpson simpson = new Bart("D'oh");
simpson.talk();
Lisa lisa = new Lisa();
lisa.talk();
((Bart) simpson).prank();
}}

Example of static Polymorphism


Method overloading is one of the way java supports static polymorphism. Here we have
two definitions of the same method add() which add method would be called is
determined by the parameter list at the compile time. That is the reason this is also known
as compile time polymorphism.

class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
}
public class Demo
{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}
}

Runtime Polymorphism (or Dynamic polymorphism)


It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in
which a call to an overridden method is resolved at runtime, thats why it is called runtime
polymorphism. I have already discussed method overriding in detail in a separate tutorial,
refer it: Method Overriding in Java.

Example
In this example we have two classes ABC and XYZ. ABC is a parent class and XYZ is a
child class. The child class is overriding the method myMethod() of parent class. In this
example we have child class object assigned to the parent class reference so in order to
determine which method would be called, the type of the object would be determined at
run-time. It is the type of object that determines which version of the method would be
called (not the type of reference).

To understand the concept of overriding, you should have the basic knowledge
of inheritance in Java.

class ABC{
public void myMethod(){
System.out.println("Overridden Method");
}
}
public class XYZ extends ABC{

public void myMethod(){


System.out.println("Overriding Method");
}
public static void main(String args[]){
ABC obj = new XYZ();
obj.myMethod();
}
}

S-ar putea să vă placă și