[go: up one dir, main page]

0% found this document useful (0 votes)
69 views44 pages

Object-Oriented Programming: Abstract Classes and Polymorphism

This document discusses abstract classes and polymorphism in object-oriented programming. It explains that abstract classes cannot be instantiated and exist to be subclassed, while concrete classes can be instantiated. Abstract classes declare common behaviors for subclasses using abstract methods that must be implemented by subclasses. Polymorphism allows the same method invocation to produce different results depending on the object type, enabling extensibility. Interfaces define common methods for unrelated classes to implement, standardizing interactions.

Uploaded by

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

Object-Oriented Programming: Abstract Classes and Polymorphism

This document discusses abstract classes and polymorphism in object-oriented programming. It explains that abstract classes cannot be instantiated and exist to be subclassed, while concrete classes can be instantiated. Abstract classes declare common behaviors for subclasses using abstract methods that must be implemented by subclasses. Polymorphism allows the same method invocation to produce different results depending on the object type, enabling extensibility. Interfaces define common methods for unrelated classes to implement, standardizing interactions.

Uploaded by

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

Object-Oriented

Programming: Abstract
Classes and
Polymorphism
Abstract Classes and Methods
 Abstract classes
– Are superclasses (called abstract
superclasses)
– Cannot be instantiated
– Incomplete
 subclasses fill in "missing pieces"
 Concrete classes
– Can be instantiated
– Implement every method they declare
– Provide specifics
2
Abstract Classes and Methods
 Purpose of an abstract class
– Declare common attributes …
– Declare common behaviors of classes in a
class hierarchy
 Contains one or more abstract methods
– Subclasses must override
 Instancevariables, concrete methods
of abstract class
– subject to normal rules of inheritance
3
 Abstract Classes
Classes that are too general to
create real objects
Used only as abstract superclasses
for concrete subclasses and to
declare reference variables
Many inheritance hierarchies have
abstract superclasses occupying the
top few levels

4
Keyword abstract

Use to declare a class abstract


Also use to declare a method
abstract
Abstract classes normally contain
one or more abstract methods
All concrete subclasses must
override all inherited abstract
methods
5
Beware! Compile Time Errors

 Attempting to instantiate an object of


an abstract class
 Failure to implement a superclass’s
abstract methods in a subclass
– unless the subclass is also declared
abstract.
6
Creating Abstract Superclass
Employee
abstract superclass Employee,

earnings is declared abstract


 No implementation can be given for earnings
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

7
Example Based on Employee
Abstract
AbstractClass
Class

Concrete
Concrete
Classes
Classes

8
Polymorphic interface for the
Employee hierarchy classes.

9
Introduction
Polymorphism
– Enables “programming in the general”
– The same invocation can produce “many
forms” of results
Interfaces
– Implemented by classes to assign common
functionality to possibly unrelated classes

10
Polymorphism
When a program invokes a method
through a superclass variable,
– the correct subclass version of the method
is called,
– based on the type of the reference stored
in the superclass variable
Thesame method name and signature
can cause different actions to occur,
– depending on the type of object on which
the method is invoked
11
Polymorphism
 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).
12
Polymorphism Promotes
Extensibility
 Software that invokes polymorphic
behavior
– 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.
13
Demonstrating Polymorphic
Behavior
Asuperclass reference can be aimed at
a subclass object
– a subclass object “is-a” superclass object
– the type of the actual referenced object,
not the type of the reference, determines
which method is called

14
Polymorphism
 Promotes extensibility
 New objects types can respond to
existing method calls
– Can be incorporated into a system without
modifying base system
 Only
client code that instantiates the
new objects must be modified
– To accommodate new types

15
Example Based on Employee
Abstract
AbstractClass
Class

Concrete
Concrete
Classes
Classes

16
Example
 Employee [] employees = new Employee [4];
 employees[0] = new CommisionEmployee();

 employees[1] = new SalariedEmployee();

 employees[2] = new HourlyEmployee();

 employees[3] = new BaseCommEmployee();

 for ( int i=0; i<=3;i++)


{

 System.out.printf(employees[i].earnngs());
employees[i].display()); }
17
Note in Example Hierarchy
 Dynamic binding
– Also known as late binding
– Calls to overridden methods are resolved
at execution time, based on the type of
object referenced

18
Downcasting
 for ( int i=0; i<4;i++) {
 If (employees[i] instanceOf BasePlusCommisionEmployee)
 {
– BasePlusCommissionEmployee emp=
(BasePlusCommissionEmployee ) employees[i];
– emp.setBaseSalary( 1.10 *
emp.getBaseSalary() );
– S.O.P("new base salary with 10%% increase is
emp.getBaseSalary() );
– employee[i]=emp;
 }
 System.out.printf(employees[i].earnngs());
19
 } //end for
Allowed Assignment between
super and Sub class
 Assigning a super class reference to a
super class variable is straightforward.
 Assigning a subclass reference to a
subclass variable is straightforward.
 Assigning a subclass reference to a
super class variable is safe, because
the subclass object is an object of its
super class.

20
Allowed Assignment between
super and Sub class
 However, the super class variable can
be used to refer only to super class
members.

 Ifthis code refers to subclass-only


members through the super class
variable, the compiler reports errors
– Downcasting can overcome this error

21
Allowed Assignment between
super and Sub class
 Attempting to assign a super class
reference to a subclass variable is a
compilation error.

 Toavoid this error, the super class


reference must be cast to a subclass
type explicitly.

22
Superclass And Subclass
Assignment Rules
 Assigning a superclass reference to
superclass variable straightforward
 Subclass reference to subclass variable
straightforward
 Subclass reference to superclass variable
safe
– because of is-a relationship
– Referring to subclass-only members through
superclass variables a compilation error
 Superclass reference to a subclass variable a
compilation error
– Downcasting can get around this error
23
Interface
 Suppose that the company involved
wishes to perform several accounting
operations in a single accounts payable
application—in addition to calculating
the earnings that must be paid to each
employee, the company must also
calculate the payment due on each of
several invoices (i.e., bills for goods
purchased).?
24
Interfaces
 Though applied to unrelated things
(i.e., employees and invoices), both
operations have to do with obtaining
some kind of payment amount.
 For an employee, the payment refers
to the employee’s earnings.
 For an invoice, the payment refers to
the total cost of the goods listed on the
invoice.
25
Interface
 Can we calculate such different things
as the payments due for employees
and invoices in a single application
polymorphically
 Interface offer a capability requiring
that unrelated classes implement a set
of common methods

26
Interfaces

27
Why Use Interfaces
 Provide capability for unrelated classes
to implement a set of common
methods
 Define and standardize ways people
and systems can interact
 Interface specifies what operations
must be permitted
 Does not specify how performed

28
What is an Interface?

 An interface is a collection of constants


and method declarations
 An interface describes a set of methods
that can be called on an object
 The method declarations do not include
an implementation
– there is no method body

29
What is an Interface?
A child class that extends a parent
class can also implement an interface
to gain some additional behavior
 Implementing an interface is a
“promise” to include the specified
method(s)
 A method in an interface cannot be
made private

30
When A Class Definition
Implements An Interface:
 It must implement each method in the
interface
 Constants from the interface can be
used as if they had been defined in the
class (They should not be re-defined in
the class)

31
Declaring Constants with Interfaces
Interfaces can be used to declare
constants used in many class
declarations
– These constants are implicitly public,
static and final

32
Implementation vs. Interface
Inheritance
Interface
Implementation
Inheritance
Inheritance
 Each new specifies
Interface subclass one
inherits
or more
one or
abstract
more methods
methods
 declared in superclass
Must be declared for each class in hierarchy

 Subclass
Overriddenuses
for superclass declarations
subclass-specific implementations

33
Creating and Using Interfaces
 Declaration begins with interface
keyword
 Classes implement an interface (and its
methods)
 Contains public abstract methods
– Classes (that implement the interface)
must implement these methods

34
Why Use Interfaces
 Java has single inheritance, only
 This means that a child class inherits
from only one parent class
 Sometimes multiple inheritance would
be convenient
 Interfaces give Java some of the
advantages of multiple inheritance
without incurring the disadvantages

35
Example

06/21/2021 Abstract classes & Interface 36


Rules

06/21/2021 Abstract classes & Interface 37


Some of Java's Most used
Interfaces
 Cloneable
– To make a copy of an existing object via
the clone() method on the class Object.
 Serializable
– Pack a web of objects such that it can be
send over a network or stored to disk. And
naturally later be restored as a web of
objects.

06/21/2021 Abstract classes & Interface 38


The Cloneable Interface
A class X that implements the
Cloneable interface tells clients that X
objects can be cloned.
 The interface is empty, i.e., has no
methods.
 Returns an identical copy of an object.

06/21/2021 Abstract classes & Interface 39


The Cloneable Interface,
Example

06/21/2021 Abstract classes & Interface 40


The Cloneable Interface,
 newCarObject = oldCarObject.clone();
– Copies newCarObject to a new memory
location

 newCarObject = oldCarObjec;
– Only assigns the reference of oldCarObjec
to newCarObject .
– No copy is made. Both objects point to
same memory location.
06/21/2021 Abstract classes & Interface 41
Summary ( Abstract vs
Interface)

06/21/2021 Abstract classes & Interface 42


Design guidelines

 Use classes for specialization and


generalization
 Use interfaces to add properties to
classes.

06/21/2021 Abstract classes & Interface 43


End

44

You might also like