0% found this document useful (0 votes)
39 views37 pages

Students CH8 Polymorphism PDF

This document discusses polymorphism and dynamic/static binding in programming languages. It begins with an overview of static and dynamic binding, then discusses how polymorphism allows the same code to work with different types of objects. The document demonstrates polymorphism through an example where a displayObject method can accept objects of different geometric shape types like Circle and Rectangle. It explains that dynamic binding means the method called is determined by the object's actual type at runtime. The document also notes benefits of polymorphism like extensibility through new subclasses.

Uploaded by

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

Students CH8 Polymorphism PDF

This document discusses polymorphism and dynamic/static binding in programming languages. It begins with an overview of static and dynamic binding, then discusses how polymorphism allows the same code to work with different types of objects. The document demonstrates polymorphism through an example where a displayObject method can accept objects of different geometric shape types like Circle and Rectangle. It explains that dynamic binding means the method called is determined by the object's actual type at runtime. The document also notes benefits of polymorphism like extensibility through new subclasses.

Uploaded by

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

CS111: Programming Language II

▪ Static/Dynamic binding

▪ Polymorphism presentation

▪ Let's practice all this…

Dr. MFH, 2023 2


▪ Up to now, we executed programs where type of objects or class to

which objects belong is known at compile time. → This is called

static binding.

We can say that overloaded methods are bonded using static

binding.

Dr. MFH, 2023 3


▪ We have also the situation where the type of object being used is

determined at runtime. . → This is called dynamic binding.

We can say that overridden methods are bonded using dynamic

binding.

Dr. MFH, 2023 4


▪ Static/Dynamic binding

▪ Polymorphism presentation

▪ Let's practice all this…

Dr. MFH, 2023 5


▪ Meaning: Poly = many Morph = shape

Polymorphism:

Ability for the same code to be used with


different types of objects and behave
differently with each

Dr. MFH, 2023 6


We have the following hierarchy, and we suppose that all the
classes code is already written.
In the main class, we will define the method display

Dr. MFH, 2023 7


public class PolymorphismDemo
{
/**** Display geometric object properties *********/
public static void displayObject(GeometricShape objectDemo)
{
System.out.println("Created on " + objectDemo.getClass());
System.out.println("Created on " + objectDemo.getDateCreated());
System.out.println("Color is " + objectDemo.getColor());
}

Method displayObject takes a parameter of the GeometricShape type.


Will be invoked passing any instance of GeometricObject.
An object of a subclass can be used wherever its superclass object is
used.
Let's see that →
Dr. MFH, 2023 8
public class PolymorphismDemo
{
/************** Display geometric object properties *********/
public static void displayObject(GeometricShape objectDemo)
{
System.out.println("Created on " + objectDemo.getClass()); System.out.println("Created on " + objectDemo.getDateCreated());
System.out.println("Color is " + objectDemo.getColor());
}

/************ Main method ************/


public static void main(String[] args)
{ Instances of
// Display circle and rectangle properties GeometricShape
displayObject(new Circle(1, "red"));
displayObject(new Rectangle(1, 1, "black"));
}
}
Polymorphic call of displayObject method.
We can invoke displayObject by passing any instance of GeometricShape.
An object of a subclass can be used wherever its superclass object is used.

Dr. MFH, 2023 9


OUTPUT

objectDemo.getClass()

objectDemo.getDateCreated()--- In the class GeometricShape


initialzed with:
dateCreated = new java.util.Date();

Dr. MFH, 2023 10


▪ When a superclass variable contains a reference to a subclass object, and
that reference is used to call a method, the subclass version of the method
is called.

▪ When the compiler encounters a method call made through a variable, the
compiler determines if the method can be called by checking the variable’s
class type.
▪ If that class contains the proper method declaration (or inherits one),
the call is compiled.

▪ At execution time, the type of the object to which the variable refers
determines the actual method to use: dynamic binding.

Dr. MFH, 2023 11


▪ With polymorphism, we can design and implement systems that are
easily extensible

▪ New classes can be added with little or no modification to the


general portions of the program, as long as the new classes are part
of the inheritance hierarchy that the program processes generically.

▪ The only parts of a program that must be changed to accommodate


new classes are those that require direct knowledge of the new
classes that we add to the hierarchy.

Dr. MFH, 2023 12


▪ Static/Dynamic binding

▪ Polymorphism presentation

▪ Let's practice all this…

Dr. MFH, 2023 13


▪ Static/Dynamic binding

▪ Polymorphism presentation

▪ Let's practice all this…

Dr. MFH, 2023 14


Dr. MFH, 2023 15
NOTE: In class, the students will work on the main important topics, and they
MUST FINISH coding the whole case study on NetBeans.

Tasks
1 Write the headers of all the classes and interface of the diagram
2 Write the Interface code
Write StudentActivity class, it will not implement the interface method.
3
The studentLevel must be between 1 and 9
4 Write Employee classes, it will not implement the interface method.
Write the second level classes. The class socialActivity will not implement the
5
interface method. The constrains will be provided in the corresponding slides.
deduceGrade method will be implemented in class GradedActivity and overridden in
PassFailActivity. It has been written in a chapter 3, so students can rewrite the same.
NOTE: Write all the toString methods in a way that all the needed data will be
printed in the main.
6 Write the main class methods. Details will be given in the corresponding slide.
7 Finish coding the whole project for next class
Dr. MFH, 2023 16
Tasks
1 Write the headers of all the classes and interface of the diagram

Dr. MFH, 2023 17


Tasks
1 Write the headers of all the classes and interface of the diagram

Dr. MFH, 2023 18


Tasks
2 Write the Interface code

public interface Payable

Dr. MFH, 2023 19


Tasks
Write StudentActivity class, it will not implement the interface method.
3
The studentLevel must be between 1 and 9.

public abstract class StudentActivity implements Payable{

…………………………………→

Dr. MFH, 2023 20


Tasks
Write StudentActivity class, it will not implement the interface method.
3
The studentLevel must be between 1 and 9.

…………………………………

}
Dr. MFH, 2023 21
Tasks
4 Write Employee classes, it will not implement the interface method.

public abstract class Employee implements Payable{

}
Dr. MFH, 2023 22
Tasks
Write the second level classes. The class socialActivity will not implement the
5
interface method. class GradedActivity. Override the toString method.

public class GradedActivity extends StudentActivity


{

…………………………………→ 23
Dr. MFH, 2023
Tasks
5 Write the second level classes. The class socialActivity will not implement the interface method. class GradedActivity

The amount depend on the score: • >= 70 → basicPayment+10%


• >= 90 → basicPayment+20% • >= 60 → basicPayment+5%
• >= 80 → basicPayment+15% • Fail: basicPayment-30%

…………………………………
@Override
public double getPaymentAmount(){
if (getScore()>=90){return getBasicPayment()+getBasicPayment()*0.2;}
else if(getScore()>=80){return getBasicPayment()+getBasicPayment()*0.15;}
else if(getScore()>=70){return getBasicPayment()+getBasicPayment()*0.1;}
else if(getScore()>=60){return getBasicPayment()+getBasicPayment()*0.05;}
else { return getBasicPayment()*0.7; }
}
…………………………………→

Dr. MFH, 2023 24


Tasks
Write the second level classes. The class socialActivity will not implement the
5
interface method. class GradedActivity. Override the toString method.

…………………………………
public char deduceGrade()
{ // Same code as in Chapter 3 }
@Override
public String toString(){

Dr. MFH, 2023 25


}
Tasks
Write the second level classes. The class socialActivity will not implement the
5
interface method. class SocialActivity

public abstract class SocialActivity extends StudentActivity


{

} Dr. MFH, 2023 26


Tasks
Write the second level classes. The class socialActivity will not implement the
5 interface method. class SalariedEmployee.
getPaymentAmount() in SalariedEmployee will return the weeklySalary

public class SalariedEmployee extends Employee{

…………………………………→
Dr. MFH, 2023 27
Tasks
Write the second level classes. The class socialActivity will not implement the
5 interface method. class SalariedEmployee
getPaymentAmount() in SalariedEmployee will return the weeklySalary

…………………………………

@Override
public String toString() {

}
} Dr. MFH, 2023 28
Method/Class
Finish coding the whole project for next class
8
NOTES to consider in your work:
NOTE: getPaymentAmount()in Training:
If nbhours > minhours, the Paymentamount will be the product of number of hours
with the hourpayment.
And if not online, we add 20% to the payment amount
NOTE: DeduceGrade in Assignement will return T if submission is true, F otherwise.
NOTE: In Exam constructor: the score value will be calculated and then it will be
used to set the score field.
• Declare a local variable for the score calculation.
• Calculate points for each question and numeric score for this exam. We suppose that
the total is over 100.
• pointsByQuestion = 100.0 / nbquestions;
• Score calculation formula = 100.0 - (nbMissedQuestions * pointsByQuestion);
• Set the score with the calculation result.

Dr. MFH, 2023 29


Tasks

6 Write the main class methods. Details will be given in the corresponding slide.

1. The main class will contain the following methods: main, menu, FillList,
DisplayList.
2. The method menu(), will display a menu for the user.

3. The method FillList will take the user choices and create and add the objects in
the list.
4. The method DisplayList:

▪ will polymorphically invoke the toString method.

▪ while displaying, it will verify if the current element is an instance of the


class Exam, if it is true, it we will create a variable of type Exam that will
contain the current exam object. Then we will change the minimum passing
score to be 70% of the actual value. We print the result.

Dr. MFH, 2023 30


public static void main(String[] args)

menu();

ArrayList<Payable> MyList = new ArrayList<Payable>();

FillList(MyList);

DisplayList(MyList);

Dr. MFH, 2023 31


The main class will contain:
▪ Method menu(), that will display a menu for the user. Hint: the colored printouts
are done with the following instruction:
System.out.println("\u001B[41m" + "************** Menu
**************" + "\u001B[47m");

Dr. MFH, 2023 32


The main class will contain:
▪ A method FillList, with the following signature:
public static void FillList(ArrayList<Payable> L)
This method will add objects in the arraylist based on the user choice, using switch.
The stop condition will be when the user will insert 0.

Dr. MFH, 2023 33


The main class will contain:

▪ A method DisplayList, with the following signature:

public static void DisplayList(ArrayList<Payable> L)

This method will Display all the arraylist elements.

While looping inside the arraylist, we will verify if the current element is an
instance of class Exam.

If yes, we will create a variable and process a downcasting (Slide 36) on it.

Write the three methods.

Dr. MFH, 2023 34


The instanceof keyword checks whether an object is an instance of a
specific class or an interface.
The instanceof keyword compares the instance with type.
The return value is either true or false.

Dr. MFH, 2023 35


▪ Downcasting is a casting (i.e., explicitly tell the compiler to convert
an object of supertype into an object of subtype (derived class))
from a superclass to a subclass.
▪ In other words, it means the typecasting of a parent object to a child
object.

Usage
Downcasting is used when we want to
perform some specific operation in a
generalised method depending upon the
subtype of object.

Dr. MFH, 2023 36


37

Text Book:
Chapter 10

Dr. MFH, 2023

You might also like