POLYMORPHISMChapter 6
Chapter 5
6.0 Polymorphism Polymorphism concept Abstract classes and methods Method overriding Concrete sub classes and methods Array of super classes Interfaces
Polymorphism concept
Polymorphism means “having many forms” It is the ability to use the same name to refer to methods
that perform different tasks. Ability of a variable to have more than one type – hold
values of different types. Let us code generically like parameter, it lets us write
code that is both general and tailored to a particular situation.
Polymorphism concept
Advantages :- Allows different (but related) objects the flexibility to
respond differently to the same message. Allow objects to treat other objects in a general way. Code sharing
Disadvantages :- When you use it, you must treat different objects in a
general way Just by looking at the source code, it is not possible to
determine which code is executed.
Polymorphism concept
To expand the usage and the effectiveness of polymorphism, we have to apply the concept of abstract class and the array
Method Overriding:a subclass inherits methods from a superclass, and the subclass modify the implementation of a method defined in the superclass
Method Overloadingdefine multiple methods with the same name but different signatures
Abstract Class
Is a class that can only be used as a base class for another class, that is, no objects of an abstract class can be instantiated.
Allows programmer to describe the methods and data that should be in the class.
Must contain at least one abstract method to ensure that an object cannot be instantiated which contain incomplete method.
It may contain any number and combination of abstract and nonabstract methods.
Is a hybrid of a interface and class. It is like interface - is not completely implemented and
cannot be instantiated but it is still a class.
Abstract Class
An abstract class is a common solution when we know the subclass is likely to override the superclass.
Main reason :- To avoid redundant codes Several concrete classes have some common code that can
be implemented in a single superclass. A class is declared as abstract by including the keyword abstract in the class’s header line, example:
abstract class student {
}
Abstract Class
Similar to a concrete class :- Is compiled with a bytecode file xyz.class if the class name is xyz. Has either public, protected, private or package
accessibility Cannot be public unless it has the same name as its source code
file. Serves as type for declaring variables and parameters May include constructors May include methods, classes and interfaces
Difference to a concrete class :- May contain abstract method Cannot be instantiated
Abstract Methods
Describes a behavior or action for a method in the abstract class. Defining a method that is deferred. Specified in the parentclass but must be implemented in a child class. Has no code body, no braces { } – contains only a header line. A placeholder that requires all derived classes to override and complete
the method. All of the abstract methods must be overridden by methods in the concrete
(complete) subclasses. Advantage : conceptual – allows the programmer to think of an activity as
associated with an abstraction at a higher level. An abstract methods cannot be declared as either static or final. Example :
abstract public void getmessage();
Example of abstract class and method
public abstract class Shape { private double x, y; public abstract double getArea(); public abstract double getCircumference(); public double getX(){ return x; }
public double getY(){ return y; }
public void setX(double x){ this.x = x; } public void setY(double y){ this.y = y; }}
public abstract class Card{ String recipient; public abstract void greeting();}
Example of abstract class and method
class HariRaya extends Card{ public HariRaya(String r){ recipient = r; }
public void greeting(){ System.out.println(“Dear “ + recipient +
“ , \n Selamat Hari Raya”); }}
class Birthday extends Card{public Birthday(String r){ recipient = r;
}
public void greeting(){ System.out.println(“Dear “ + recipient +
“ , \n Happy Birthday”); }}
class CardApp { public static void main(String[]
args) { Card c; c = new Birthday(“Miss X”); c.greeting(); c = new HariRaya(“Mr Y”); c.greeting(); }}
Array in Polymorphism
Similar to implement the array in the inheritance concept. But we want the reference of array which is comes from the parent class.
You might want to create a superclass reference and treat subclass objects as superclass objects so you can create an array of different objects that share the same ancestry.
Manipulate an array of subclass objects by invoking the appropriate method for each subclass.
Elements in a single array must be of the same type.
Array in Polymorphism
From the previous slide example – CardApp
class CardArrayApp { public static void main(String[] args) { Card[] c = new Card[12];
Birthday B = new Birthday(“Miss X”); HariRaya H = new HariRaya(“MR Y”);
c[0] = B; c[1] = H;
for (int j = 0; j <= 1; j++) c[j].greeting();
} }
Method Overriding
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, not the superclass’s old definition.
The overriding method must have the same name, arguments and return type as the overriden method.
Typically used for abstract method.
Can occur in two different forms :-
Replacement A method can replace the method in parent class. Code in parent class is not executed
at all.
Refinement Combines the code from parent and child class – the use of keyword super (constructor)
Interface
Consists of constants and abstract methods only. Cannot be instantiated Purpose to specify a set of requirements for classes to implement. Requirements as a “contract” between implementing class and any client
class that uses it. Important part of OOD is to create the interface when class
implementation will be done later. Description of a capability List the methods that a class must implement to carry out that capability. A class may implement several interfaces An interface may be implemented by several classes All abstract methods declared in an interface must be public and abstract.
Interface
Different from class :- Declared only method headers and public constants Has no constructors Cannot be instantiated Can be implemented by class Cannot implement an interface Cannot extend a class Can extend several other interfaces.
Interface
Has the general syntax :interface interfacename{ //constant declarations;
//abstract method declarations;}
A class that is derived from an interface by using keyword implementsclass classname implements interfacename{
//override definitions of all abstract //methods;
}
Example : Interface
public abstract class Animal{
} public class Dog extends Animal {
} public interface Worker{ } public class WorkingDog extends Dog implements Worker {
} public class DemoWorkingDog{
}
19
Superclass: Animal
Subclass: Dog
Interface: Worker
Subclass: WorkingDog
Application
Output ?