Você está na página 1de 29

Polymorphism

Polymorphism is derived from two Greek words called poly


and morphism.
 Poly means many and
 morphism means form, behavior or structure.
The word polymorphism means the ability to take more than
one form.
In Java, polymorphism refers to the fact that you can have
multiple methods with the same name in the same class. this
means that a particular operation may behave differently for
different sub-classes of the same class.
Cont.’
 Subclasses of a class can define their own unique behaviors and
yet share some of the same functionality of the parent class.
 Polymorphism is the ability to refer to an object using either to
actual form or a parent form.
 Polymorphism enables us to “program in the general” rather than
“program in the specific.”
 “Polymorphism is an old code that reuses new code.”
There are two kinds of polymorphism:
 Overloading
 Overriding
Polymorphism using Overridden methods
 Inheriting or extending a class is a very good approach for factoring
out common functionality between classes.
 Specific classes extending more general classes for allowing code to
be reused in a project.
 helps to keep the project more maintainable and less prone to bugs as
the development cycle progresses.
 Any time you have a class that inherits a method from a superclass,
you have the opportunity to override the method (unless, the method is
marked final).
 The key benefit of overriding is the ability to define behavior that's
specific to a particular subclass type.
rules of method overriding
 The new method definition must have the same method
signature, i.e., the method name, and the types and the number of
parameters, including their order, are the same as in the
overridden method.
 The new method definition cannot narrow the accessibility of the
method, but it can widen it.
 You cannot override a method marked final.
 You cannot override a method marked static.
 If a method can't be inherited, you cannot override it. Remember
that overriding implies that you're re implementing a method you
inherited!
 The return type must be the same.
Example
 class Animal {  This is called overriding a
public static void main(String args[]) { method
Animal animal = new Animal();
Dog dog = new Dog();  Method print in Dog
animal.print(); overrides method print
dog.print();
} in Animal
void print() {  A subclass variable can
System.out.println("Superclass Animal");
} shadow a superclass
} variable, but a subclass
 public class Dog extends Animal { method can override a
void print() {
System.out.println("Subclass Dog");
superclass method.
}
}
Polymorphism using Overloading methods
Overloaded methods let you to reuse the same method name
in a class, but with different arguments (and optionally, a
different return type). Java permits you to reuse a method
name for more than one method.

The rules for making overloaded methods are:

 Argument list must differ.

 Return types can be different .

A method can be overloaded in the same class or in a subclass.


Cont.’
Example
 class Test {
public static void main(String args[]) {
myPrint(5);
myPrint(5.0);
}
 static void myPrint(int i) {
System.out.println("int i = " + i);
}
 static void myPrint(double d) { // same name, different parameters
System.out.println("double d = " + d);
}
}
Invoking Overloaded Methods
When a method is invoked, more than one method of the same name
might exist for the object type that you invoke.

 For example, the Student class might have four methods with the same
name but with different argument lists, which means the method is
overloaded.

 To explore this, let’s add gradeAverage methods to Student class. Here


our assumption is a student takes at least four courses per semester and
seven at most. the methods used to calculate the average grade have a
single name with different number of parameters.
Cont.’
Abstract Classes and Methods
So far, all the examples presented use concrete classes.
 A concrete class is a regular class that can be instantiated.
 Java has another class type called an abstract class.
 An abstract class is different from a concrete class because it
cannot be instantiated and must be extended.
 In some cases, it is useful to declare classes for which the
programmer never intends to instantiate objects. Such classes are
called abstract classes.
 Because they are used only as superclasses in inheritance
hierarchies called abstract superclasses. These classes cannot be
used to instantiate objects, because abstract classes are
incomplete.
Cont.’
An abstract class is important to
 provide an appropriate superclass from which other classes can inherit
and share a common design.
 establish common elements in a class that is too general to instantiate.
For example MemberOfEce class have common attributes and methods
for all members of the Department (Students, lecturers, Technical
Assistants and Administrative staffs).
This class should be general but it is incomplete.
Hence, we may not need to instantiate objects using the class rather we
use as a super class. Therefore it is better creating this class as abstract
class.
Cont.’
 Public abstract class MemberOfEce{ }
//An abstract class can be sub classed.
 Public class Student extends MemberOfEce{ }
//An abstract class can not be instantiated.
 MemberOfEce mel = new MemberOfEce();// error

An abstract class may contain abstract methods.


Abstract methods are methods that are not implemented. They have a
valid method signature but must be overridden and implemented in the
class that extends the abstract class.
An abstract method is one with keyword abstract in its declaration.
Example
Cont.’
Generally abstract methods :
 Cannot have a method body
 Must be declared in abstract class
 Is overridden in subclass
 When a child class inherits an abstract method, it is inheriting a
method signature but no implementation.
 An abstract method is a way to guarantee that any child class will
contain a method with a matching signature.
NB, A class that contains any abstract methods must be declared as an
abstract class even if that class contains some concrete (non abstract)
methods.
Constructors and static methods cannot be declared abstract.
Interface
Java interface allows us to define a common behavior among classes.
Any class which implements an interface must implement the behaviors
define in the interface.
In its most common form, an interface is a group of related methods with
empty bodies. An interface is a contract.
 Interfaces can be implemented by any class, from any inheritance tree
 To implement interface, you have to use the implements keyword in
the class declaration.
 All interface methods must be implemented, and must be marked
public.
 an abstract class can define both abstract and non-abstract methods
but an interface can have only abstract methods.
cont.’
Rules of interface
 All interface methods are implicitly public and abstract. In other
words, no need of actually type the public or abstract modifiers in the
method declaration, but the method is still always public and abstract.
 All variables defined in an interface must be public, static, and final.
in other words, interfaces can declare only constants not instance
variables.
 Interface methods must not be static.
 Because interface methods are abstract, they cannot be marked final.
 An interface can extend one or more other interfaces.
 An interface cannot extend anything but another interface.
 An interface cannot implement another interface or class.
 An interface must be declared with the keyword interface.
 Interface types can be used polymorphically.
Example
public abstract interface Registration { }
//legal interface class declaration.
 Abstract modifier is considered redundant since interfaces are
implicitly abstract whether you type abstract or not.
public abstract interface Registration { }
public interface Registration { }
 The above two interface declarations are identical.
 The public modifier is required if you want the interface to have public
rather than default access.
 Typing public and abstract modifiers on the methods is redundant,
since all interface methods are implicitly public and abstract.
Cont.’
The following five method declarations, if declared within their own
interfaces, are legal and identical!
void register();
public void register();
abstract void register();
public abstract void register();
abstract public void register();
The following interface method declarations won't compile:
final void register();
static void register ();
private void register ();
public protected void register();
Declaring Interface Constant
 You're allowed to put constants in an interface.
 interface constants are defined in an interface, they must be public,
static, and final.
 any variable defined in an interface must be and implicitly is a public
constant.
Example,
interface Registration {
int NUMBER_OF_STUDENT = 62;
void countRegisterd();
}
class Student implements Registration {
public void countRegisterd() {
NUMBER_OF_STUDENT = 27;
}}
Cont.’
 Once the value has been assigned, the value can never be modified.
 The assignment happens in the interface itself (where the constant is
declared), so the implementing class can access it and use it.
 So the NUMBER_OF_STUDENT = 27 assignment will not compile.
The following are all identical:
public int x = 1; // Looks non-static and non-final, // but isn't!
int x = 1; // Looks default, non-final, // non-static, but isn't! static
int x = 1; // Doesn't show final or public
final int x = 1; // Doesn't show static or public
public static int x = 1; // Doesn't show final
public final int x = 1; // Doesn't show static
static final int x = 1; // Doesn't show public
public static final int x = 1; // what you get implicitly
Example
interface Registration //interface declaration
{
Void register(float avgGrade); //interface methods
Void withdrawal();
Void drop();
Void add();
}
cont.’
public void Student implements Registration
{
public void register(float avgGrade){
if (avgGrade>2.0)
System.out.println(“student successfully registered”);
else
System.out.println(“student can not be registered”);
}
public void withdrawal(){
System.out.println(“Implementation for withdrawal”);
}
public void add(String course){
System.out.println(course+“Added”);
}
public void drop(String course){
System.out.println(course +“Dropped!!!”);
}
}
cont.’
public class pg extends Student{
public pg(){}
public void register(float avgGrade){
if(avgGrade>3.0)
System.out.println(“student successfully registered”);
else
System.out.println(“student can not be registered”);
}
}
cont.’
public class TestInterface
{
public static void main(String [] args) //main method
{
Registration stud= new Student();
Registration pgStud= new pg();
System.out.println(“Student ug”);
System.out.println(“ ”);
stud.register(2.5f);
stud.add(“object oriented programming”);
stud.dropp(“Introduction to computing”);
System.out.println(“Student pg”);
System.out.println(“ ”);
pgStud.register(2.5f);
pgStud.withdrawal();
}
}
The difference b/n abstract class and interface
 Abstract class can have static, final ,non static and non final variables
but interface has only static and final variables.
 Abstract class can be used as single inheritance but interface is used to
achieve multiple inheritance.
 Abstract class can have static methods, main methods and constructor
but interface does not have the above three.
 Abstract class can provide implement the interface but the reverse is
impossible.
 Abstract class can have abstract and non abstract method but interface
has only abstract methods.
 The abstract keyword is used to declare abstract class and interface
keyword is used to declare interface.
cont.’
 Members in an interface is public by default but abstract class may
contain non public members.
 Interface is used to “implements” where as abstract class is used to
“extends”.
 Interface can extends another interface but abstract class can extends
another class and implements multiple interface.
 Interface is more flexible than abstract class because one class can
extends only one super class but implements multiple interfaces.
End of this Chapter
I Wish

Thank You For


Your Attention!
All Peace

For