0% found this document useful (0 votes)
7 views

chapter7-Polymorphism (1)

Uploaded by

2023856682
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

chapter7-Polymorphism (1)

Uploaded by

2023856682
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 29

Polymorphism Concept

Abstract Classes And Methods


Method Overriding
Concrete Subclasses and
Methods
Array of superclasses

1
 Polymorphism means “having many forms”

 One object (of superclass) has ability to appear in many forms (object of
subclasses)

 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.
 Allows multiple objects of different subclasses to be treated as objects
of single superclass, while automatically selecting the proper methods to
apply to a particular object based on the subclass it belongs to.
 The ability of reference variable to change behavior according to what
object instance it is holding
2
 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.

3
 To expand the usage and the effectiveness
of polymorphism, we can apply the concept
of abstract class and the array

4
 Class Person hierarchy

Person

Student Employee

5
6
7
8
9
 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. Its purpose is
to be a parent to several related classes. The child classes
inherit from the abstract parent class.You can only declare
a reference variable of an abstract class type.
 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.
 You can instantiate an object of a subclass of an abstract class, but only if
the subclass gives the definitions of all the abstract methods of the
superclass

10
 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 :

abstract class student { ….. }

11
 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

12
 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 :
public void abstract getmessage() { …}

13
 A non-abstract child class inherits the abstract method and must define a
non-abstract method that matches the abstract method.

 An abstract child of an abstract parent does not have to define non-


abstract methods for the abstract signatures it inherits.

14
 Example
public abstract class Card
{
String recipient;
public abstract void greeting();
}

The abstract class can include abstract methods and non-abstract m


contains even one abstract method, then the class itself has to be d

15
public class Birthday extends Card{
public Birthday( String r ){
super(r);
}
public void greeting(){
System.out.println(“Dear “ + recipient +
“ , \n Happy Birthday”);
}
}

Birthday is a non abstract child of an abstract parent. Objects ca


from it. Its constructor implicitly calls the no-argument construct
parent, Card, which calls the constructor in Object
16
 Birthday inherits the abstract method greeting() from its parent.
 Birthday must define a greeting() method that includes a method
body (statements between braces).
 The definition of greeting() must match the signature given in the
parent.
 If Birthday did not define greeting(), then Birthday must be declared
as an abstract class.
 This would make it an abstract child of an abstract parent.

17
 A non-abstract child must override each abstract method inherited (all
abstract methods) from its parent by defining a method with the same
signature and same return type.
▪ This is called concrete subclasses, used to emphasize the fact that it
is not abstract.

 A child may define additional methods with signatures different from


the parent's method.

 It is an error if a child defines a method with the same signature as a


parent method, but with a different return type.

18
 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)

19
public abstract class Card { class HariRaya extends Card {
protected String recipient; public HariRaya(String r)
{ recipient = r; }
public abstract void greeting();
} public void greeting()
{ System.out.println(“Dear “ + recipient +
“ , \n Selamat Hari Raya”); }
class Birthday extends Card {
public Birthday(String r) The application class :
{ recipient = r; }
class CardApp {
public void greeting() public static void main(String[] args) {
{ System.out.println(“Dear “ + recipient + Card c;
“ , \n Happy Birthday”); } c = new Birthday(“Rashid”);
} c.greeting();
c = new HariRaya(“Siti”);
c.greeting();
}

20
 Concrete subclasses: write all the definitions of abstract methods
that have in the abstract superclass and can be instantiated

21
 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.

22
 From the previous slide example – CardsApp

class CardApp {
public static void main(String[] args) {

Card[] c = new Card[12];

Birthday B = new Birthday(“Abraham”);


HariRaya H = new HariRaya(“Wahid”);

c[0] = B;
c[1] = H;

for (int j = 0; j <= 1; j++)


c[j].greeting();

23
 Can be declared to hold objects of different subclasses

24
25
 Is used to determine the class of an object (which subclass is
currently point by object reference of superclass)

 Example
 To find out the number of students whose cgpa more than 3.5
Person p = new Student();
if(p instanceof Student){
System.out.println(“P is a student”); }
else {
System.out.println(“P is an employee”); } }
int student = 0;
for(int i=0; i<5<;i++) {
if(person[i] instanceof
Student) {
26
student++; } }
27
instanceof

Use cast operator to make sure p[i] points


to an object of subclass EmployeePoly

Declaration of object em for class


EmployeePoly as a temporary object that will
used to call method getSal() in EmployeePoly
class

28
 Write the definition for the super and subclass below:
 Super class: Car (abstract)
▪ 2 attributes:(name and color)
▪ 2 abstract methods: (display:void and calculate_price:double)
 Sub class: Perodua (non abstract)
▪ 2 attributes: price and tax
▪ Overrides abstract methods (display() and calculate price())
▪ display() : to display the information of perodua cars
including total price
▪ calculate_price() : to calculate total price of car after adding
tax into car price.
 Main method: test the program to display the output.

29

You might also like