0% found this document useful (0 votes)
26 views

Chapter 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Chapter 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Chapter 5: Polymorphism –is the ability of an object to take on many forms.

In java Achieved using Method Overriding and Method Overloading.

1. Method Overloading:-java Allows method to overloaded. Method overloading occurs when


class has two or more methods with the same name but different parameter list. On calling a
method, at first java matches up the method name and the number and type of parameter to
decide which one of the definition to execute. This process is known as Compile time
Polymorphism.

For method overloading, we provide several different method definition in the class with the same
name but different parameter list.

In method overloading, we need to remember Certain Points.

You can overload a method as long as the parameter lists are distinct enough for the complier to
able to distinguish which method you want to invoke. Certainly if the number of parameters is
different, the overloading is valid as shown in the following two Method Signatures (Method Header
without Definition)
public double volume(double l, double w, double h );//three Parameters

public double volume(double l);//one parameter

If we simply change the name parameters, is not valid

Changing the order of parameter list is just like changing the parameter list example of valid
overloading

Public void area(int x,int y,long z);

Public void area(log a,int b,int c);

classOverload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
classMethodOverloading
{
publicstaticvoid main (Stringargs [])
{
OverloadObj = newOverload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}

2) Method Overriding
Child class has the same method as of base class. In such cases child class overrides
the parent class method without even touching the source code of the base class. This
feature is known as method overriding.

classVehicle{
publicvoid move (){
System.out.println("Vehicles are used for moving from one place to another ");
}
}

classCarextendsVehicle{
publicvoid move (){
super.move();// invokes the super class method
System.out.println("Car is a good medium of transport ");
}
}

publicclassTestCar{
publicstaticvoid main (Stringargs[]){
Vehicle b =newCar();// Vehicle reference but Car object
b.move();//Calls the method in Car class
}
}

Abstract Class
A class which contains the abstract keyword in its declaration is known as
abstract class.
 Abstract classes may or may not contain abstract methods, i.e., methods
without body ( public void get(); )

 But, if a class has at least one abstract method, then the class must be declared
abstract.

 If a class is declared abstract, it cannot be instantiated.

 To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.

If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.

publicabstractclassEmployee{
privateString name;
privateString address;
privateint number;

publicEmployee(String name,String address,int number){


System.out.println("Constructing an Employee");
this.name = name;
this.address= address;
this.number= number;
}

publicdoublecomputePay(){
System.out.println("Inside Employee computePay");
return0.0;
}

publicvoidmailCheck(){
System.out.println("Mailing a check to "+this.name +" "+this.address);
}

publicStringtoString(){
return name +" "+ address +" "+ number;
}

publicStringgetName(){
return name;
}

publicStringgetAddress(){
return address;
}

publicvoidsetAddress(StringnewAddress){
address=newAddress;
}

publicintgetNumber(){
return number;
}
/* File name : AbstractDemo.java */
publicclassAbstractDemo{

publicstaticvoid main(String[]args){
/* Following is not allowed and would raise error */
Employee e =newEmployee("George W.","Houston, TX",43);
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}
ERROR:Employee is abstract; cannot be instantiated

Inheriting the Abstract Class


/* File name : Salary.java */
publicclassSalaryextendsEmployee{
privatedouble salary;// Annual salary

publicSalary(String name,String address,int number,double salary){


super(name, address, number);
setSalary(salary);
}

publicvoidmailCheck(){
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to "+getName()+" with salary "+ salary);
}

publicdoublegetSalary(){
return salary;
}

publicvoidsetSalary(doublenewSalary){
if(newSalary>=0.0){
salary=newSalary;
}
}

publicdoublecomputePay(){
System.out.println("Computing salary pay for "+getName());
return salary/52;
}
}

Here, you cannot instantiate the Employee class, but you can instantiate the
Salary Class, and using this instance you can access all the three fields and
seven methods of Employee class as shown below.
/* File name : AbstractDemo.java */
publicclassAbstractDemo{
publicstaticvoid main(String[]args){
Salary s =newSalary("MohdMohtashim","Ambehta, UP",3,3600.00);
Employee e =newSalary("John Adams","Boston, MA",2,2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}

Output
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to MohdMohtashim with salary 3600.0

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Abstract Methods
If you want a class to contain a particular method but you want the actual
implementation of that method to be determined by child classes, you can
declare the method in the parent class as an abstract.

 abstract keyword is used to declare the method as abstract.

 You have to place the abstract keyword before the method name in the method
declaration.

 An abstract method contains a method signature, but no method body.

 Instead of curly braces, an abstract method will have a semoi colon (;) at the
end.

Example
publicabstractclassEmployee{
privateString name;
privateString address;
privateint number;

publicabstractdoublecomputePay();
// Remainder of class definition
}

Suppose Salary class inherits the Employee class, then it should implement
the computePay() method as shown below −

/* File name : Salary.java */


publicclassSalaryextendsEmployee{
privatedouble salary;// Annual salary

publicdoublecomputePay(){
System.out.println("Computing salary pay for "+getName());
return salary/52;
}
// Remainder of class definition
}

Interface

It is a collection of abstract methods. A class implements an interface, thereby


inheriting the abstract methods of the interfaceA.

An interface is similar to a class in the following ways −

 An interface can contain any number of methods.

 An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.

 The byte code of an interface appears in a .class file.

 Interfaces appear in packages, and their corresponding bytecode file must be in


a directory structure that matches the package name.
However, an interface is different from a class in several ways, including −

 You cannot instantiate an interface.

 An interface does not contain any constructors.

 All of the methods in an interface are abstract.

 An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.

 An interface is not extended by a class; it is implemented by a class.

 An interface can extend multiple interfaces.

A interface is Not a class. A class describes the attributes and behaviors of an


object. An interface contains behavior that a class implements.

Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple
example to declare an interface −

Example
Following is an example of an interface −

/* File name : NameOfInterface.java */


importjava.lang.*;
// Any number of import statements

publicinterfaceNameOfInterface{
// Any number of final, static fields
// Any number of abstract method declarations\
}

Interfaces have the following properties −

 An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword
is not needed.

 Methods in an interface are implicitly public.

Example
/* File name : Animal.java */
interfaceAnimal{
publicvoid eat();
publicvoid travel();
}

Implementing Interfaces
When a class implements an interface, you can think of the class as signing
a contract, agreeing to perform the specific behaviors of the interface. If a
class does not perform all the behaviors of the interface, the class must
declare itself as abstract.

A class uses the implements keyword to implement an interface. The


implements keyword appears in the class declaration following the extends
portion of the declaration.

Example
/* File name : MammalInt.java */
publicclassMammalIntimplementsAnimal{

publicvoid eat(){
System.out.println("Mammal eats");
}

publicvoid travel(){
System.out.println("Mammal travels");
}

publicintnoOfLegs(){
return0;
}

publicstaticvoid main(Stringargs[]){
MammalInt m =newMammalInt();
m.eat();
m.travel();
}
}

Output
Mammal eats
Mammal travels

Difference between abstract class and interface

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.

4) Abstract class can have static methods, main Interface can't have static methods, main method
method and constructor. or constructor.

5) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.

6) The abstract keyword is used to declare abstract class. The interface keyword is used to declare
interface.

7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves
fully abstraction (100%).

Example of abstract class implementing interfaces in


Java
Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods

interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}
/Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}

//Creating subclass of abstract class, now we need to provide the implementation of rest
of the methods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
//Creating a test class that calls the methods of A interface
class Test5{
public static void main(String args[]){
A a=new M(); a.a(); a.b(); a.c(); a.d();
}}
Output:
I am a
I am b
I am c
I am d

Q) Multiple inheritance is not supported through class in java but it


is possible by interface, why?
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

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.

1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void show();
7. }
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
8. public void show(){System.out.println("Welcome");}
9.
10. public static void main(String args[]){
11. A7 obj = new A7();
12. obj.print();
13. obj.show();
14. }
15. }
16. Output:Hello
17. Welcome

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. }

You might also like