Chapter 6 - part 2
Chapter 6 - part 2
Object-Oriented Programming
Chapter 6 – Part 2
Learning Outcomes
At the end of this chapter, you should be able to
Explain polymorphism, dynamic binding, and generic programming.
Describe casting and explain why explicit downcasting is necessary.
Restrict access to data and methods using the protected visibility
modifier.
Prevent class extending and method overriding using the final
modifier.
2
1. Subtypes and Supertypes
A class defines a type.
A type defined by a subclass is called a subtype.
A type defined by its superclass is called a supertype.
The type of a variable is called its declared type.
A variable of a reference type can hold a null value or a reference to
an object.
eg : int count; GeometricObject
GeometricObject obj;
Circle c1;
Circle Rectangle
2. Polymorphism (1)
The term “polymorphism” is Greek meaning “of many forms”.
Cn Cn-1 ..... C2 C1
Demo 6.5\TestPolymorphismCasting
5. The protected Modifier (1)
The protected modifier can be applied on data and methods in a
class.
A protected data or a protected method in a public class can
be accessed by any class in the same package or its subclasses, even
if the subclasses are in a different package.
Visibility increases
public
protected -
default - -
private - - -
Visibility Modifiers
A Subclass Cannot Weaken the Accessibility
A subclass may override a protected method in its superclass and change its
visibility to public.
However, a subclass cannot weaken the accessibility of a method defined in the
superclass.
E.g., if a method is defined as public in the superclass, it must be defined as
public in the subclass. public class Employee{
….
public void calculateSalary(){
…
}
}
public class Manager extends Employee{
….
public void calculateSalary(){
…
}
}
6. The final Modifier
The modifiers are used on classes and class members (data and
methods), except that the final modifier can also be used on local
variables in a method.
A final local variable is a constant inside a method.
public class Circle {
private double radius;
protected String color;
public Circle() { }
public Circle(double radius){
this.radius = radius; }
…….
public double getArea() {
final double PI = 3.142;
double area= radius * radius * PI;
return area;
}
}
The final Modifier
A final class cannot be extended:
final class Math {
...
}
The final variable is a constant:
final static double PI = 3.14159;
The final method cannot be overridden by its subclasses.
public final double myFormula() { …}
MyMath
MyAlgebra
To Do
Review the slides and source code for this chapter.
Read up the relevant portions of the recommended text.
Do the tutorial and complete the remaining practical
questions for this chapter.
We shall selectively discuss them during class.