Week 03 Polymorphism&AbctractClasses
Week 03 Polymorphism&AbctractClasses
INTRODUCTION TO
COMPUTING II
CHAPTER - 8
Polymorphism
– To understand the concept of polymorphism.
– To understand the concept of static or early binding.
– To understand the concept of dynamic or late binding.
– To learn about upcasting and down-casting.
Abstract Classes
– To learn about abstract classes.
– To understand how to inherit abstract classes.
– To understand how to override abstract methods inherited
from abstract superclass.
2
1 - Polymorphism
3
Introduction to Polymorphism
• There are three main programming mechanisms that constitute
Object‐Oriented Programming (OOP): 1) encapsulation, 2)
Inheritance, 3) Polymorphism
• Polymorphism is the ability to associate many meanings to one
method name.
– through a special mechanism known as late binding or dynamic binding
4
Cont…
What is Binding?
•Binding refers to the process of associating a method definition with a
method invocation.
1. If the method definition is associated with the method invocation when the
code is compiled, that is called static or early binding.
2. If the method definition is associated with the method invocation when the
method is invoked (at run time), that is called late binding or dynamic
binding.
6
Cont…
• Upcasting:
– Upcasting is the typecasting of a child object to a parent
object.
– Upcasting can be done implicitly.
– Upcasting gives us the flexibility to access the parent class
members but it is not possible to access all the child class
members using this feature. Instead of all the members,
we can access some specified members of the child class.
For instance, we can access the overridden methods.
• Downcasting:
– Downcasting means the typecasting of a parent object to
a child object.
– Downcasting cannot be done implicitly… it should be done
explicitly.
7
class Parent { // Parent class Example-1:
String name;
void method() { // Prints the signature of the parent class
System.out.println("Method from Parent called");
}
}
class Child extends Parent { // Child class
int id;
@Override
void method() { // Overrides parent method to print signature of child class
System.out.println("Method from Child called");
}
}
public class CastingDemo { // Demo class to see diff. b/n upcasting and downcasting
public static void main(String[] args) {
// Upcasting implicitly // What we normally do in
Parent p = new Child(); main ()
Parent x = new Parent();
p.name = “Father"; x.name = "Mr.X";
// p.id = 1; // id is not accessible // x.id = 0 ; // no id in
System.out.println(p.name); Parent
p.method(); x.method();
Child y = new Child();
// Trying to Downcasting Implicitly y.name = "Mr..Y";
// Child c = new Parent(); -> compile time error
y.id = 0 ;
y.method();
// Downcasting Explicitly A better approach is
Child c = (Child)p; if ( p instanceof Child )
Child c = (Child)p;
c.id = 1; OUTPU
System.out.println(c.name); pName= Father
System.out.println(c.id); Method from Child called
c.method(); cName= Father
}
} cID= 1
Method from Child called 8
Cont…
• From the example we can observe the following points:
1. Syntax of Upcasting:
Parent p = new Child();
2. Upcasting will be done internally and due to upcasting the
object is allowed to access only parent class members and
child class specified members (overridden methods, etc.) but
not all members.
// id is not accessible p.id = 1;
3. Syntax of Downcasting:
Child c = (Child)p;
4. Downcasting has to be done explicitly / externally and due to
downcasting a child object can acquire the properties of the
parent object.
c.name = p.name;
// i.e., c.name = “Father"
9
Polymorphism
• Polymorphism is derived from 2 Greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So
Polymorphism means “many forms”.
• The terms polymorphism and late binding are essentially just
different words for the same concept.
• In Java, polymorphism refers to the dynamic binding mechanism
that determines which method definition will be used when a
method name has been overridden.
• The term polymorphism refers to the processes of assigning
multiple meanings to the same method name using late binding.
• Thus, polymorphism is implemented using late binding.
1
Polymorphism (Cont.)
• A reference variable of a superclass type can point to an object of its subclass (known as upcasting).
– You can treat an object of a subclass as an object of its superclass.
• These reference variables have many forms, that is, they are polymorphic reference variables.
• They can refer to objects of their own class or to objects of the classes inherited from their class.
• But…
• You cannot automatically make reference variable of subclass type point to object of its superclass. You need typecasting.
• If reference variable of superclass does not point to a subclass object in first place and you use a cast operator on it to make a reference variable of the subclass point to the object, then Java will
throw a ClassCastException—indicating that the class cast is not allowed.
1
Polymorphism (Cont.)
• Example:
if ( p instanceof Child )
Child c = (Child) p;
1
Polymorphism (Cont.)
The final Modifier
•You can declare a method of a class final using the keyword
final.
1
Upcasting and Downcasting
• Upcasting occurs when an object of a derived class is assigned
to a variable of a base class (or any ancestor class).
1
Upcasting and Downcasting
• Downcasting occurs when a type cast is performed from a base
class to a derived class (or from any ancestor class to any
descendent class).
– Downcasting must be done very carefully.
– In many cases it doesn't make sense, or is illegal !!
1
Dynamic Binding
• Different objects can invoke different method definitions using the same
method name.
• The type of object being referenced at the time of the method call, not the
type of reference that was declared, determines which method is invoked.
• For example: Figure f;
Box b = new Box(1, 4, 4);
f = b;
f.drawAt(2);
Triangle t = new Triangle(1,2);
f = t;
f.drawAt(2);
1
Type Checking and Dynamic Binding
• However, you can invoke only a method in class Person with the
variable p.
1
Type Checking and Dynamic Binding (Cont.)
• The variable determines what methods can be used, but the type
referenced by the object determines which definition of the
method will be used.
• Example:
Employee e = (Employee) p;
e.setEmployeeNumber(5678);
1
• However, even a type cast cannot fool Java!
Example:
Box b = new Box(1, 4, 4);
Figure f = (Figure) b;
f.drawHere();
• The above piece of code will use the definition of the method
drawHere() given in class Box, not the definition of
drawHere() given in class Figure.
2
Dynamic Binding with the toString() Method
2
Subtle Difference
2
• In object oriented programming, "is a" relationship denotes
“one object is a type of another”.
– A derived class demonstrates an "is a" relationship between itself and its
base class.
– Forming an "is a" relationship is one way to make a more complex class
out of a simpler class. For example, an HourlyEmployee “ is an"
Employee where HourlyEmployee is a more complex class and
Employee is more general class.
2
2 - Abstract Classes
2
Abstraction in Java
• Abstraction is a process of hiding the implementation
details and showing only functionality to the user.
• It shows only essential things to the user and hides the
internal details.
• Abstraction lets you focus on what the object does instead
of how it does it.
• For example, sending SMS where you type the text and
send the message. You don't know the internal processing
about the message delivery.
• There are two ways to achieve abstraction in java:
1. Abstract classes.
2. Interface.
29
2
Abstract Classes in Java
Abstract Class:
•An abstract class is a class with one or more abstract
methods. An abstract class must have the modifier
abstract included in the class heading, as illustrated by
the following example.
•EXAMPLE:
30
3
Abstract Classes in Java (Cont.)
Abstract Class:
•A class which is declared as abstract is known as an
abstract class.
•It needs to be extended and its method is
implemented.
•It cannot be instantiated: an abstract class is not
intended to be used to create objects.
•It can have abstract and non-abstract methods.
•If one of the methods in a class is abstract, then the
class must be declared abstract.
•In contrast with the term abstract class , a class with no
abstract methods is called a concrete class. 31
3
Abstract Classes in Java (Cont.)
• Abstract method does not have any body, even
empty body, but does end with a semicolon in
place of a method body.
• Keyword abstract:
• Used to declare a class abstract.
• Also used to declare a method abstract.
– Abstract classes can contain:
all abstract methods.
one or more abstract methods.
all concrete methods.
– All concrete subclasses must override all
inherited abstract methods.
32
3
Abstract Classes in Java (Cont.)
• In Java, an abstract method cannot be private.
Normally an abstract method is public but protected, and
package (default) access is allowed.
• By declaring one or more methods to be abstract and by
omitting the method body, only objects of derived classes
which override the method(s) can be instantiated.
public abstract void drawHere();
public abstract void doSomething(int count);
34
3
Abstract Classes in Java (Cont.)
• Failure to implement a superclass’s abstract methods in a
subclass is a compilation error unless the subclass is also
declared abstract.
• Example:
36
3
Implementing an Abstract Method
(Cont.)
In the previous example, the class Shape is an abstract class,
and the implementation of its method draw( ) is provided by the
Rectangle and Circle1 classes.
37
3
Example-2: Implementing an Abstract Method
(Cont.)
• Define the speak( ) method as abstract in the superclass Animal.
public abstract class Animal {
protected String kind; // Cow, cat, etc.
public Animal() { }
public String toString() {
return "I am a " + kind + "and I go" + speak();
}
public abstract String speak(); // Abstract method
}
public class Cat extends Animal public class Cow extends Animal
{ public Cat() { { public Cow() {
kind = "cat"; kind = "cow";
} }
public String speak() { public String speak() {
return "meow"; return "moo";
} }
} }
38 code…
• Write an application class with main () to test this 3
Example-3: Implementing a
salary system
40
4
Abstract Class Employee: Outline
public abstract class Employee { Declare abstract class Employee
private String firstName;
private String lastName; Attributes common to all employees
private String socialSecurityNumber;
public Employee(String first, String last, String ssn)
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
}
public void setFirstName(String first) {
firstName = first;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String last) {
lastName = last;
}
public String getLastName() {
return lastName;
} 41
4
Abstract Class Employee: Outline (Cont.)
public void setSocialSecurityNumber(String ssn)
{
socialSecurityNumber = ssn;
}
// complete it as an exercise
}
// complete it as an exercise
}
} 46
4