[go: up one dir, main page]

0% found this document useful (0 votes)
15 views45 pages

Week 03 Polymorphism&AbctractClasses

Uploaded by

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

Week 03 Polymorphism&AbctractClasses

Uploaded by

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

CSE 201

INTRODUCTION TO
COMPUTING II

CHAPTER - 8

POLYMORPHISM & ABSTRACT


CLASSES
Lecture Objectives

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

• Inheritance allows a base class to be defined, and other classes


derived from it.
– Code for the base class can then be used for its own objects, as well as objects
of any derived classes.
• Polymorphism allows changes to be made to method definitions in
the derived classes, and have those changes apply to the software
written for the base class.

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.

•Method to be executed is determined at execution time, not compile


time.
•Java uses late binding for all methods except for a few cases (private,
final, and static methods).
5
Cont…
Upcasting Vs Downcasting in Java
•Just like the datatypes (e.g., int x= (int) 10.3333; ) , the
objects can also be typecasted. However, in objects,
there are only two types of objects (i.e.) parent object
and child object. Therefore, typecasting of objects
basically mean that one type of object (i.e.) child or
parent to another.

•Two types of typecasting.


1. Upcasting
2. Downcasting

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

• The operator instanceof determines whether a reference


variable that points to an object is of a particular class type.

• Example:
if ( p instanceof Child )
Child c = (Child) p;

• This expression evaluates to true if p points to an object of the


class Child; otherwise it evaluates to false.

1
Polymorphism (Cont.)
The final Modifier
•You can declare a method of a class final using the keyword
final.

public final void doSomeThing() {


//……………
}

• If a method of a class is declared final, it cannot be


overridden with a new definition in a derived class.
• You can also declare a class final using the keyword
final.
• If a class is declared final, then no other class can be
derived from this class.
• Java does not use late binding for methods that are
private, marked final, or static.
1
Polymorphism (Cont.)
• In x.getMeasure(), which method will be called depends on
the actual object.
– If x refers to a BankAccount, then it calls:
BankAccount.getMeasure()
– If x refers to a Coin, then it calls:
Coin.getMeasure()

• Polymorphism (many shapes): Behavior can vary depending on


the actual type of an object.

• Called late binding : resolved at runtime.

• Different from overloading ; overloading is resolved by the


compiler (early binding)

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

Vehicle v; // base class


Car c = new Car(); // derived class
v = c; // upcasting
v.identify(); // prints car

• Or we could do something equivalent, such as:

Vehicle v = new Car ();

• Because of late binding, identify() uses the definition of


identify() given in the Car 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 !!

void doSomething(Vehicle v1) {


Car c1 = (Car) v1; // could generate an er
c1 = v1; // will generate an error
}

• There are times when downcasting is necessary; e.g., inside the


equals method for a class.
– How can we make sure a Vehicle is a Car?

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);

• If the reference b references a Box object and the reference t references a


Triangle object, b and t invoke different definitions of the method drawAt()
even if b and t are declared to be of type Figure.

1
Type Checking and Dynamic Binding

• Recall that an object reference to an ancestor class can refer to an


object of a descendant class.

Employee e = new Employee();


Person p;
p = e;

• However, you can invoke only a method in class Person with the
variable p.

• If a method is overridden in the class Employee, and variable p


references an Employee object, then the method in class
Employee is used.

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.

• To use a method name in the class Employee with an object


named by the variable p of type Person, use a type cast.

• 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

• Recall that the method toString() typically is used to


prepare and return a string, describing an object, for
output to the screen.

• The name of this method can be omitted, thanks to


dynamic binding, because one definition of method
println() expects a single argument of type Object
which it uses to invoke the method toString()
associated with the object.

2
Subtle Difference

• Dynamic binding refers to the process carried out by


the computer.

• Polymorphism can be thought of as something objects


do.

• Polymorphism, encapsulation, and inheritance, are


considered to be the main features of object-oriented
programming.

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.

• Another way to make a more complex class out of a simpler class


is through a "has a" relationship.
– This type of relationship, called composition, occurs when a class contains
an instance variable of a class type.
– In object orientation design, we can say “class A is in "has a" relationship
with class B if class A holds reference of Class B”. For example, a Car class
may contain instance variables such as tires, and seats, which are
objects form the Tire and Seat classes.
2
• Polymorphism enables programmers to deal in generalities and
let the execution-time environment handle the specifics.
• Programmers can command objects to behave in manners
appropriate to those objects, without knowing the types of the
objects (as long as the objects belong to the same inheritance
hierarchy).
• Software invoking polymorphic behavior is independent of the
object types to which messages are sent.
• New object types that can respond to existing method calls can be
incorporated into a system without requiring modification of the
base system.
• Only client code that instantiates new objects must be modified
to accommodate new types.
2
1 // PolymorphismTest.java
2 // Assigning superclass and subclass references to superclass and
3 // subclass variables.
4
5 public class PolymorphismTest
6 {
7 public static void main( String args[] )
8 {
9 // assign superclass reference to superclass variable
10 CommissionEmployee cmnEmp_1 = new CommissionEmployee (
11 "Sue", "Jones", "222-22-2222", 10000, .06 );
12 Typical reference assignments
13 // assign subclass reference to subclass variable
14 BasePlusCommissionEmployee bpcEmp = new BasePlusCommissionEmployee (
15 "Bob", "Lewis", "333-33-3333", 5000, .04, 300 );
16
17
18 // invoke toString on superclass object using superclass variable
Note:-
19 System.out.printf( "%s %s:\n\n%s\n\n",
This code is given
20 "Call CommissionEmployee's toString with superclass reference ",
only to explain the
21 "to superclass object", cmnEmp_1.toString() );
polymorphism.
22
It is an incomplete
23 // invoke toString on subclass object using subclass variable
code which will not
24 System.out.printf( "%s %s:\n\n%s\n\n", compile and run.
25 "Call BasePlusCommissionEmployee's toString with subclass", You need to define
26 "reference to subclass object", all the 5 classes of
27 bpcEmp.toString() ); the hierarchy to
28 compile it.
2
29 // invoke toString on subclass object using superclass variable
30 CommissionEmployee cmnEmp_2 = bpcEmp;
31
Assign a reference to a bpcEmp object to a
32 System.out.printf( "%s %s:\n\n%s\n",
CommissionEmployee variable
33 "Call BasePlusCommissionEmployee4's toString with superclass",
34 "reference to subclass object", cmnEmp2.toString() );
35 } // end main
36 } // end class PolymorphismTest Polymorphically call
basePlusCommissionEmployee’s
toString method

Call CommissionEmployee's toString with superclass reference to superclass object:

commission employee: Sue Jones


social security number: 222-22-2222
gross sales: 10000.00
commission rate: 0.06

Call BasePlusCommissionEmployee's toString with subclass reference to


subclass object:

base-salaried commission employee: Bob Lewis


social security number: 333-33-3333
gross sales: 5000.00
commission rate: 0.04
base salary: 300.00

Call BasePlusCommissionEmployee's toString with superclass reference to


subclass object:

base-salaried commission employee: Bob Lewis


social security number: 333-33-3333
gross sales: 5000.00
commission rate: 0.04
base salary: 300.00

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:

public abstract class Employee {


private String name;
private Date hireDate;
public abstract double getPay();
……………

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);

• A class that has at least one abstract method must be


declared abstract.
• However, a class could be always declared abstract
without having any abstract method.
33
3
PITFALL: You Cannot Create Instances of an Abstract Class

• You cannot use an abstract class constructor to create an


object of the abstract class.
• You can only create objects of the derived classes of the
abstract class.
• Attempting to instantiate an object of an abstract
class is a compilation error.

public abstract class Employee {


…………
}

Employee joe = new Employee(); // Compilation error


// Illegal because Employee is an abstract class

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:

abstract class Shape {


public abstract void drawHere();
......
}

class Rectangle extends Shape {


// The method drawHere() is NOT implemented!
......
}
35
3
Example-1: Implementing an Abstract
Method

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.

Mostly, we don't know about the implementation class (which is


hidden to the end user), and an object of the implementation class
is provided by the factory method.

A factory method is a method that returns the instance of the


class. We will learn about the factory method later.

In the example, if you create an instance of the Rectangle class,


draw( ) method of Rectangle class will be invoked.

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

UML Inheritance Diagrams for Employee Class

• Creating Abstract Superclass: Employee


 earnings method is declared as an abstract.
• No implementation can be given for earnings method in the
Employee abstract class.
 An array of Employee variables will store references to
subclass objects.
• earnings method calls from these variables will call the
appropriate version of the earnings method. 39 3
Cont…

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

public String getSocialSecurityNumber()


{
return socialSecurityNumber;
}
abstract method earnings()
public String toString() has no implementation
{
return String.format( "%s %s\nsocial security number: %s",
getFirstName(), getLastName(), getSocialSecurityNumber());
}

public abstract double earnings(); // no implementation here

} // End of class Employee


42
4
Extending Concrete Classes

public class SalariedEmployee extends Employee {


private double weeklySalary;
// …
// calculate earnings; override abstract method earnings in Employee
public double earnings()
{
return getWeeklySalary();
}
// …
} 43
4
Extending Concrete Classes (Cont.)

public class CommissionEmployee extends Employee {


private double grossSales;
private double commissionRate;
public double earnings()
{
return getCommissionRate()* getGrossSales();
}
}
44
4
Extending Concrete Classes (Cont.)

public class HourlyEmployee extends Employee {


private double wage; // wage per hour
private double hours; // hours worked for week
public double earnings()
{
if ( getHours() <= 40 ) // no overtime
return getWage() * getHours();
else
return 40*getWage()+(getHours()-40)*getWage()* 1.5;
}
} 45
4
Extending Concrete Classes (Cont.)

public class BasePlusCommissionEmployee extends CommissionEmployee

// complete it as an exercise
}

public class TestEmpolyeeApp {

public static void main (String args [ ] ) {

// complete it as an exercise
}
} 46
4

You might also like