0% found this document useful (0 votes)
18 views26 pages

Chapter 6 - part 2

Chapter 6 of the document covers inheritance and polymorphism in object-oriented programming, focusing on concepts like polymorphism, dynamic binding, and generic programming. It explains the importance of casting, access modifiers, and the final modifier in class design. The chapter concludes with practical examples and a summary of accessibility modifiers in Java.

Uploaded by

tanxx-wm23
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)
18 views26 pages

Chapter 6 - part 2

Chapter 6 of the document covers inheritance and polymorphism in object-oriented programming, focusing on concepts like polymorphism, dynamic binding, and generic programming. It explains the importance of casting, access modifiers, and the final modifier in class design. The chapter concludes with practical examples and a summary of accessibility modifiers in Java.

Uploaded by

tanxx-wm23
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/ 26

BACS2023

Object-Oriented Programming

Inheritance & Polymorphism

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

Polymorphism allows methods of the same name to behave


differently within a class family.
 Polymorphism allows one method name to be used

throughout the class family, with each class implementing the


method in a way that is appropriate to its own purpose.
public class PolymorphismDemo {
Polymorphism (2) public static void main(String[] args){
m(new GraduateStudent());
m(new Student());
PolymorphismDemo m(new Person());
m(new Object());
}

public static void m(Object x) {


System.out.println(x.toString());
}
}
class GraduateStudent extends Student {
}

class Student extends Person {


public String toString() {
Output: return "Student";
}
}
Student
Student class Person extends Object {
Person public String toString() {
return "Person";
java.lang.Object@1cfb549 }
}
Polymorphism (3)
A subclass is a specialization of its superclass
 Every instance of a subclass is an instance of
GeometricObject
its superclass, but not vice versa.
 Inheritance provides an is-a relationship, i.e.

an object of a subclass can also be treated as


an object of its superclass. Circle Rectangle

Therefore, you can always assign an instance of


a subclass to a reference variable of its
superclass type. Circle c1;
 This applies to parameter passing and
Rectangle rect1
assignment of objects to object reference
variables (including array of objects). GeometricObject obj1 = c1;
GeometricObject obj2 = rect1;
public class PolymorphismDemo {
public static void main(String[] args){
Polymorphism (4) m(new GraduateStudent());
m(new Student());
 Polymorphism enables the m(new Person());
m(new Object());
design and implementation of }

systems that are easily public static void m(Object x) {


extensible and maintainable. }
System.out.println(x.toString());

 New classes can be added with }


class GraduateStudent extends Student {
minimum or no modification. }
 Programs process objects that
class Student extends Person {
share the same superclass as if they public String toString() {
are objects of the superclass. return "Student";
}
 Simplifies programming. }

class Person extends Object {


public String toString() {
return "Person";
}
}
3. Polymorphism, Dynamic Binding and Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent()); Method m takes a parameter of the
m(new Student());
m(new Person());
Object type. You can invoke it
m(new Object()); with any object.
}
public static void m(Object x) {
System.out.println(x.toString());
}
} An object of a subtype can be used
class GraduateStudent extends Student { wherever its supertype value is
}
class Student extends Person { required. This feature is known as
public String toString() { parametric polymorphism.
return "Student";
}
}

class Person extends Object {


public String toString() {
return "Person";
}
}
Polymorphism, Dynamic Binding and Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent()); When the method m(Object x) is
m(new Student()); executed, the argument x’s toString
m(new Person()); method is invoked.
m(new Object());
}  x may be an instance of
public static void m(Object x) { GraduateStudent, Student,
System.out.println(x.toString()); Person, or Object.
}
}  Classes GraduateStudent, Student,
class GraduateStudent extends Student { Person, and Object have their own
}
class Student extends Person {
implementation of the toString
public String toString() { method.
return "Student";  Which implementation is used will be
}
} determined dynamically by the JVM at
runtime. This capability is known as
class Person extends Object { dynamic binding.
public String toString() {
return "Person";
}
} PolymorphismDemo
Dynamic Binding
 Suppose an object o is an instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a
subclass of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn.
 That is, Cn is the most general class, and C1 is the most specific class.
 In Java, Cn is the Object class.
 If o invokes a method p, the JVM searches the implementation for the method p in
C1, C2, ..., Cn-1 and Cn, in this order, until it is found.
 Once an implementation is found, the search stops and the first-found implementation is
invoked.

Cn Cn-1 ..... C2 C1

Since o is an instance of C1, o is also an


Object instance of C2, C3, …, Cn-1, and Cn
Method Matching vs. Binding
 Matching a method signature and binding a method implementation are two different
issues.
 Matching a method signature
 The declared type of the reference variable decides which method to match at
compile time.
 The compiler finds a matching method according to parameter type, number of
parameters, and order of the parameters at compilation time.
 Binding a method implementation
 A method may be implemented in several subclasses. The JVM dynamically binds
the implementation of the method at runtime.
 The actual class of the object referenced by the variable decides which method
implementation should be bound during runtime.

GeometricObject obj= new Circle(7.5);


System.out.println(obj.toString());
Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
 Writing methods which can be
m(new GraduateStudent()); used generically for a wide range
m(new Student());
m(new Person()); of object arguments.
m(new Object());
}
 This is known as generic
public static void m(Object x) { programming.
System.out.println(x.toString());
}  If a method’s parameter type is a
}
class GraduateStudent extends Student { superclass (e.g., Object), you
} may pass an object to this method
class Student extends Person {
public String toString() { of any of the parameter’s
return "Student"; subclasses (e.g., Student or
}
} String).
class Person extends Object {
public String toString() {
return "Person";
}
}
4. Casting Objects – Implicit Casting
 You have already used the casting operator to convert variables of one primitive type to
another.
double x=9; // implicit casting
int y = (int) x; // explicit casting
 Casting can also be used to convert an object of one class type to another within an inheritance
hierarchy.
 E.g. :
Object o = new Student(); // Implicit casting

The statement Object o = new Student(),


known as implicit casting, is legal because an instance of
Student is automatically an instance of Object.
Casting Objects – Explicit Casting
 E.g., you want to assign the object reference o to a variable of the Student
type using the following statement:
Object o = new Student(); // Implicit casting
Student b = o; // Compilation error
 This is because a Student object is always an instance of Object, but an
Object is not necessarily an instance of Student. Even though you can
see that o is really a Student object, the compiler is not so clever to know
it. To tell the compiler that o is a Student object, use an explicit casting.
 The syntax is similar to the one used for casting among primitive data types -
enclose the target object type in parentheses and place it before the object to
be cast, as follows:
Student b = (Student)o; // Explicit casting
Downcasting Objects
 Assigning an instance of a superclass to a reference variable of its subclass
without an explicit cast is a compilation error (see Student.java).

Object o = new Student(); // Implicit casting


Student b =(Student) o; // Downcasting

 There is a need to (down)cast the reference stored in the superclass variable


back to a reference of the subclass type.
 When downcasting an object, a ClassCastException occurs if at execution
time the object does not have an is-a relationship with the type specified in the
cast operator.
 An object can be cast only to its own type or to the type of one of its
superclasses.
 To check that the object is indeed an object of an appropriate subclass type,
use the instanceof operator.
The instanceof Operator
Use the instanceof operator to test whether an object is an
instance of a class:
GeometricObject myObject = new Circle();

. . . //some lines of code

// Perform casting if myObject is an instance of Circle


if (myObject instanceof Circle) {
System.out.println(“The circle diameter is “ +
((Circle)myObject).getDiameter());
. . .
}
else if (myObject instanceof Rectangle) {
…..
}
TIP
To help understand casting, you may also consider the analogy of
fruit, apple, and orange with the Fruit class as the
superclass for Apple and Orange.
 An apple is a fruit, so you can always safely assign an instance of Apple
to a variable for Fruit.
 However, a fruit is not necessarily an apple, so you have to use explicit
casting to assign an instance of Fruit to a variable of Apple.

Are the following statements valid?


Fruit f=new Apple();
Apple app = new Apple();
app = f;
Example:
Demonstrating Polymorphism and Casting
 This example creates two geometric objects: a circle, and a
rectangle
 Invokes the displayGeometricObject method to display
the objects.
 The displayGeometricObject displays the area and
diameter if the object is a circle, and displays area if the object
is a rectangle.

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

private, none (if no modifier is used), protected, public


The protected Modifier (2)
 Protected data or methods in a class can be
accessed by any of its subclass, e.g.

// In the superclass Rectangle.java


protected double width; Rectangle
protected double height;
. . .
Cube

// In the subclass Cube.java


public Cube (double w, double h,
double d){
width = w; Direct access to the
height = h; Superclass instance
depth = d; variable
}
Accessibility Summary
Visibility modifiers are used to control where data and methods
may be accessed.
Modifier Accessed Accessed Accessed Accessed
on members from the from the from a from a different
in a class same class same package subclass package

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.

You might also like