Cos 202
Cos 202
COS 202
b. Runtime Polymorphism:
Runtime polymorphism occurs when a subclass provides a specific
implementation for a method that is already defined in its superclass.
This is achieved through method overriding.
A source code example follow in the next slide
// Usage
Animal myDog = new Dog(); // object of Dog class
Animal myCat = new Cat(); // object of Cat class
Disadvantages of Polymorphism
One of the disadvantages of polymorphism is that developers find it difficult to implement
polymorphism in codes.
Run time polymorphism can lead to the performance issue as machine needs to decide
which method or variable to invoke so it basically degrades the performances as decisions
are taken at run time.
Polymorphism reduces the readability of the program. One needs to identify the runtime
behavior of the program to identify actual execution time.
// Usage
Shape rectangle = new Rectangle(4, 5);
3. Interfaces in Java:
An interface in Java is a collection of abstract methods that can be
implemented by any class. It provides a way to achieve multiple
inheritance in Java.
Example:
public interface Shape {
public double area();
public double perimeter();
}
That is, we can define a class with certain attributes (and/or behaviors)
and then specify which other classes share those same attributes
(and/or behaviors).