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

CH 05 OOP Polymorphism

Polymorphism allows objects to take on multiple forms. It is achieved through method overriding, where the proper method to call is determined at runtime based on the actual object type. This allows a parent class reference to refer to child class objects. Abstract classes can contain abstract methods that are declared without an implementation, requiring subclasses to provide the implementation.

Uploaded by

sondos
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)
24 views26 pages

CH 05 OOP Polymorphism

Polymorphism allows objects to take on multiple forms. It is achieved through method overriding, where the proper method to call is determined at runtime based on the actual object type. This allows a parent class reference to refer to child class objects. Abstract classes can contain abstract methods that are declared without an implementation, requiring subclasses to provide the implementation.

Uploaded by

sondos
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/ 26

Object Oriented Programming

10636212

Dr. Ashraf Armoush

© 2020 Dr. Ashraf Armoush

Chapter 05:

Object Oriented Programming

- Polymorphism -

© 2020 Dr. Ashraf Armoush


Polymorphism
• Polymorphism is the ability of an object to take on many forms.

• The most common use of polymorphism in OOP occurs when a


parent class reference is used to refer to a child class object.

• Polymorphism enables us to write programs that process objects that


share the same superclass in a class hierarchy as if they are all objects
of the superclass

• Polymorphism is achieved by method overriding.

• Dynamic (or late) method binding: When you override methods, java
determines the proper methods to call at the program’s run time, not
at the compile time.

• Polymorphism is briefly described as "one interface, many


implementations."

© 2020 Dr. Ashraf Armoush , An-Najah National University 3

Polymorphism (cont.)
• Because Rectangle, Oval and Tria
ngle are derived from Shape, they Shape
are themselves Shapes. + getArea()

• It is legal to store a Rectangle


object in a Shape object
reference because a Rectangle is
also a Shape.
Rectangle Circle Triangle
+ drawShape() + drawShape() + drawShape()
• a Shape reference containing
+ getArea() + getArea() + getArea()
an object of a subclass of
Shape, but you don't know
what exactly the object is. Shape shape = new Rectangle();
or
Shape shape = new Circle();
• The program will resolve or
Shape shape = new Triangle();
the correct method
reference at runtime. shape.getArea();
© 2020 Dr. Ashraf Armoush , An-Najah National University 4
Polymorphism (cont.)
• You can assign a superclass reference to a subclass object;
Shape s = new Circle();
• If the object of the subclass has overridden a method in the superclass:
– If the variable makes a call to that method the subclass’s version of the
method will be run.
S.getArea();//the Circle’s getArea method will be called
• You can’t assign a superclass object to a subclass reference:
Circle c = new Shape();// Error
Circle c = (Circle) new Shape(); //Error
• If you have a subclass object that has been previously assigned to a
superclass reference and you would like to assign this object again to a
subclass reference, then you have to use casting operator
Circle c2 = s;// Error
Circle c3 = (Circle) s;
• If a subclass object is assigned to a superclass reference, you can
invoke the methods defined in the superclass only.
– You cannot invoke methods defined in the subclass.
S.drawShape();//Error
© 2020 Dr. Ashraf Armoush , An-Najah National University 5

Example:
• Superclass : Shape
– Methods:
• getArea()
• Subclasses: Circle, Rectangle
– Methods
• getArea() // overridden
• drawShape() // new method
class Shape {
public double getArea()
{
return 0.0;
}
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 6


Example (cont.)
class Circle extends Shape {
private int x,y;
private double radius;
public Circle() {
x = y = 0;
radius = 0.0;
}
public Circle(int x, int y, double radius) {
this.x=x;
this.y=y;
this.radius = radius;
}
public void drawShape() {
System.out.println("Circle.drawShape()");
}
public double getArea() {
double area = Math.PI* radius * radius;
System.out.println("Circle area="+area);
return area;
}
}
© 2020 Dr. Ashraf Armoush , An-Najah National University 7

Example (cont.)
class Rectangle extends Shape {
private int x,y,h,w;
public Rectangle() {
x = y = h = w = 0;
}
public Rectangle(int x, int y,int h, int w) {
this.x=x;
this.y=y;
this.h=h;
this.w=w;
}
public void drawShape() {
System.out.println("Rectangle.drawShape()");
}
public double getArea() {
double area = w * h;
System.out.println("Rectangle area="+area);
return area;
}
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 8


Example (cont.)
public class ShapeTest {
public static void main(String[] args) {
Shape s = new Shape();
Circle c = new Circle(0,0,10.0); //create a circle object with r=10
Rectangle r = new Rectangle(0,0,5,4);//create a rectangle object
System.out.println("Return value="+ s.getArea());
s = c ; //assign a circle object to a shape reference
System.out.println("Area= "+ s.getArea());
//s.drawShape(); // Error: you can not access the new defined methods
// with a superclass ref.
s = r ; //assign a rectangle object to a shape reference
System.out.println("Area= "+ s.getArea());
//Rectangle r2 = s ; // error
//Rectangle r3 = (Rectangle) new Shape();// Error

Rectangle r4 = (Rectangle) s; // s is superclass reference but it


// refers to a subclass object
r4.getArea(); Return value=0.0
} Circle area=314.1592653589793
} /// Area= 314.1592653589793
Rectangle area=20.0
Area= 20.0
© 2020 Dr. Ashraf Armoush , An-Najah National University Rectangle area=20.0 9

final Methods and Classes


• final methods
– Cannot be overridden
– private methods are implicitly final
– static methods are implicitly final
• final classes
– Cannot be superclasses
– Methods in final classes are implicitly final
– e.g., class String

© 2020 Dr. Ashraf Armoush , An-Najah National University 10


Static Method Hiding
• If a subclass defines a static method with the same
signature as a static method in the superclass, then
the method in the subclass hides the one in the
superclass.
• The distinction between hiding a static method and overriding
an instance method has important implications:
– The version of the overridden instance method that gets invoked is
the one in the subclass.
• (Dynamic Binding)

– The version of the hidden static method that gets invoked depends on
whether it is invoked from the superclass or the subclass.
• (Static Binding)

© 2020 Dr. Ashraf Armoush , An-Najah National University 11

Static Method Hiding (cont.)

public class A {
public static void m()
{
System.out.println("Inside class A");
}
}

public class B extends A {


public static void m()
{
System.out.println("Inside class B");
}
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 12


Static Method Hiding (cont.)
public class StaticMethodTest {
public static void main(String args[])
{
A ra1 = new A();
A ra2 = new B();
B rb = new B();

ra1.m();//static binding: reference of type A


Inside class A
ra2.m();//static binding: reference of type A
rb.m(); //static binding: reference of type B Inside class A
System.out.println(); Inside class B
ra1 = ra2;
ra1.m(); //static binding: reference of type A Inside class A
System.out.println();
A.m(); Inside class A
B.m(); Inside class B
}
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 13

Abstract Classes and Methods


• Abstract method:
– is a method that is declared without an implementation
• (no body specification)
– Keyword abstract in its declaration, as in
public abstract void draw(); //
– Constructors and static methods cannot be declared abstract
• Abstract classes:
– A class that contains any abstract methods must be declared as
an abstract class even if that class contains some concrete
(nonabstract) methods.
• Abstract classes are designed to be derived.
– abstract class can not be instantiated.

• Concrete classes:
– Can be instantiated
– Implement every method they declare
© 2020 Dr. Ashraf Armoush , An-Najah National University 14
Abstract Classes and Methods (cont.)
• When an abstract class is subclassed (derived):
– the subclass usually provides implementations for all of
the abstract methods in its parent class.
– However, if it does not, the subclass must also be
declared abstract.
class abstrcat GraphicObject{
// declare fields
// declare non-abstract methods
abstract void draw(); //abstract method
}
Class MyGraphic extends GraphicObject{
void draw()
{
//implementation
}
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 15

Abstract Classes and Methods (cont.)

© 2020 Dr. Ashraf Armoush , An-Najah National University 16


Abstract Classes and Methods (cont.)

abstract public class Shape {


// Private member variable
private String color;

// Constructor
public Shape (String color) {
this.color = color;
}

@Override
public String toString() {
return "Shape of color=\"" + color + "\"";
}

// All Shape subclasses must implement a method called getArea()


abstract public double getArea();
}

© 2020 Dr. Ashraf Armoush , An-Njah National University 17

Abstract Classes and Methods (cont.)


public class Rectangle extends Shape {
// Private member variables
private int length;
private int width;

// Constructor
public Rectangle(String color, int length, int width) {
super(color);
this.length = length;
this.width = width;
}

@Override
public String toString() {
return "Rectangle of length=" + length + " and width=" + width + ",
subclass of " + super.toString();
}

@Override
public double getArea() {
return length*width;
}
}

© 2020 Dr. Ashraf Armoush , An-Njah National University 18


Abstract Classes and Methods (cont.)
// Define Triangle, subclass of Shape
public class Triangle extends Shape {
// Private member variables
private int base;
private int height;

// Constructor
public Triangle(String color, int base, int height) {
super(color);
this.base = base;
this.height = height;
}

@Override
public String toString() {
return "Triangle of base=" + base + " and height=" + height + ",
subclass of " + super.toString();
}

@Override
public double getArea() {
return 0.5*base*height;
}
}

© 2020 Dr. Ashraf Armoush , An-Njah National University 19

Abstract Classes and Methods (cont.)

public class TestShape {


public static void main(String[] args) {
Shape s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());

Shape s2 = new Triangle("blue", 4, 5);


System.out.println(s2);
System.out.println("Area is " + s2.getArea());

// Cannot create instance of an abstract class


Shape s3 = new Shape("green"); // Compilation Error!!
}
}

Rectangle of length=4 and width=5, subclass of Shape of color="red"


Area is 20.0
Triangle of base=4 and height=5, subclass of Shape of color="blue"
Area is 10.0

© 2020 Dr. Ashraf Armoush , An-Njah National University 20


Interface
• An interface describes a set of methods that can be
called on an object, but does not provide concrete
implementations for all the methods.
– Using interface, you can specify what class must do, but
not how it does it.
• The purpose of an interface is to specify behavior for
other classes.

© 2020 Dr. Ashraf Armoush , An-Najah National University 21

Interface (cont.)
• An interface declaration begins with the keyword
interface and contains only constants and abstract
methods.
– It cannot be instantiated, it can only be implemented by
classes or extended by other interfaces.
– all of the methods in an interface are implicitly public, (not)
static & abstract [before Java SE*8]
– All member variables are implicitly (constant) public, static
and final.
• you must provide an initialization value.
• An interface looks similar to a class, except:
– the keyword interface is used instead of the keyword class
• A class can implement one or more interfaces.
• An interface can extend any number of interfaces

© 2020 Dr. Ashraf Armoush , An-Najah National University 22


Interface (cont.)
• The general format of an interface definition:
interface InterfaceName{
// constant fields
// abstract methods
}
• When you create a class that uses an interface, you reference
the interface with the keyword implements.
• You can implement one or more interfaces.
class subClass extends superClass implements Interface1, Interface2{

// you must include code (implementation) for all methods in


// the interfaces
}

• Since by default the interface methods are public, then the


Access modifier of the overriding methods should be public.
© 2020 Dr. Ashraf Armoush , An-Najah National University 23

Interface (cont.)

• The UML notation uses a solid-line arrow linking the subclass to a


concrete or abstract superclass, and dashed-line arrow to an
interface as illustrated.

© 2020 Dr. Ashraf Armoush , An-Najah National University 24


Example 1
interface A {

public void m1(); // implicitly public, not static & abstract


}

abstract class B {
B()
{
System.out.println("Inside the Constructor of class B");
}
abstract public void m2(); // abstract method

© 2020 Dr. Ashraf Armoush , An-Najah National University 25

Example 1 (cont.)
class C extends B implements A{
C(){
System.out.println("Inside the Constructor of class C");
}
public void m1()
{
System.out.println("Inside m1 method");
}
public void m2()
{
System.out.println("Inside m2 method");
}
}
public class InterafceAbstractTest{

public static void main(String args[])


{
C c = new C();
c.m1(); Inside the Constructor of class B
c.m2(); Inside the Constructor of class C
} Inside m1 method
} Inside m2 method
© 2020 Dr. Ashraf Armoush , An-Najah National University 26
Example 2

© 2020 Dr. Ashraf Armoush , An-Najah National University 27

Example 2 (cont.)
public interface Movable {
// abstract methods to be implemented by the subclasses
public void moveUp();
public void moveDown();
public void moveLeft();
public void moveRight();
}

public class MovablePoint implements Movable {


// Private member variables
private int x, y; // (x, y) coordinates of the point

// Constructor
public MovablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "Point at (" + x + "," + y + ")";
}

// Implement abstract methods defined in the interface Movable


@Override
public void moveUp() {
y--;
}
© 2020 Dr. Ashraf Armoush , An-Najah National University 28
Example 2 (cont.)
@Override
public void moveDown() {
y++;
}

@Override
public void moveLeft() {
x--;
}

@Override
public void moveRight() {
x++;
}
}

public class TestMovable {


public static void main(String[] args) {
Movable m1 = new MovablePoint(5, 5); // upcast
System.out.println(m1);
m1.moveDown(); Point at (5,5)
System.out.println(m1); Point at (5,6)
m1.moveRight(); Point at (6,6)
System.out.println(m1);
}
}
© 2020 Dr. Ashraf Armoush , An-Najah National University 29

Interface - Summary
• An interface cannot be instantiated.
• An interface can extend another interface. Use the extends
(and not the implements) keyword for this.
• Interfaces cannot contain instance variables. If you declare a
data member in an interface, it should be initialized, and all
such data members are implicitly treated as “public static
final” members.
• An interface cannot declare static methods. It can only
declare instance methods. ????
• You cannot declare members as protected or private. Only
public access is allowed for members of an interface.
• All methods declared in an interface are implicitly considered
to be abstract. If you want, you can explicitly use the abstract
qualifier for the method. ????
• You can only declare (and not define) methods in an interface

© 2020 Dr. Ashraf Armoush , An-Najah National University 30


Java SE 8 Interface Enhancements
• Default Interface Methods
– In Java SE 8, interface may contain public default
method with concrete default implementation.
– To declare a default method, place the keyword
default before the method’s return type.
– If a class implements such an interface, the class
also receives the interface default implementation
(if any).
– When an implementing class does not override
the method, it will receive the interface’s default
implementation
© 2020 Dr. Ashraf Armoush , An-Najah National University 31

Java SE 8 Interface Enhancements (cont.)


• Static Interface Methods
– In Java SE 8, interface may contain static methods
• Functional Interfaces
– In Java SE 8, any interface containing only one
abstract method is known Functional Interface.

© 2020 Dr. Ashraf Armoush , An-Najah National University 32


Java SE 9 Interface Enhancements
• what happens if you have several default
methods on an interface with code that does
almost the same thing?
– Normally, you'd refactor those methods to call a
private method containing the shared
functionality.
• But default methods can't be private.
– Creating another default method with the shared
code is not a solution .

© 2020 Dr. Ashraf Armoush , An-Najah National University 33

Java SE 9 Interface Enhancements (cont.)


• Private Interface Methods:
– With Java 9, you can add private helper methods to interfaces to
solve this problem:

public interface MyInterface {

void normalInterfaceMethod();

default void interfaceMethodWithDefault() { init(); }

default void anotherDefaultMethod() { init(); }

// This method is not part of the public API exposed by MyInterface


private void init() { System.out.println("Initializing"); }
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 34


Software Engineering Observation

Java SE8’s and Java SE9’s interface enhancements


(which allow interfaces to contain public and private
instance methods and static methods with
implementations) make programming with interfaces
appropriate for almost all cases in which you would have
used abstract classes previously. With the exception of
fields, you get all the benefits that classes provide, plus
classes can implement any number of interfaces but can
extend only one class (abstract or concrete).

© 2020 Dr. Ashraf Armoush , An-Najah National University 35

jshell: The interactive Java REPL (Java SE 9)


• Many languages already feature an interactive Read-
Evaluate-Print-Loop (REPL)
• Java now joins this club and provides jshell
• The jshell tool provides an interactive command-line
interface for evaluating declarations, statements, and
expressions of the Java programming language.
• It facilitates prototyping and exploration of coding
options with immediate results and feedback.
• The immediate feedback of jshell makes it a great
tool to explore APIs and try out language features.

© 2020 Dr. Ashraf Armoush , An-Najah National University 36


jshell (cont.)
You can launch jshell from the console and directly start typing
and executing Java code.

© 2020 Dr. Ashraf Armoush , An-Najah National University 37

Private Constructor
• Sometimes it’s useful to declare one or more of a
class’s constructors as private.
• Preventing Object Instantiation
– You can prevent client code from creating objects of a class
by making the class’s constructors private
• The use of private constructor is to serve singleton
classes.
– A singleton class is one which limits the number of objects
creation to one.
– Using private constructor we can ensure that no
more than one object can be created at a time.

© 2020 Dr. Ashraf Armoush , An-Najah National University 38


Private Constructor (cont.)
public class SingleTonClass {
//Static Class Reference
private static SingleTonClass obj=null;
private SingleTonClass(){
/*Private Constructor will prevent the instantiation of this class directly*/
}
public static SingleTonClass objectCreationMethod(){
/*This logic will ensure that no more than one object can be created at a time */
if(obj==null){
obj= new SingleTonClass();
}
return obj;
}
public void display(){
System.out.println("Singleton class Example");
}
}

public class SingleTonClassTest {


public static void main(String args[]){
//SingleTonClass obj = new SingleTonClass();
//Object cannot be created directly due to private constructor
//This way it is forced to create object via our method where we have logic for only one object creation
SingleTonClass myobject= SingleTonClass.objectCreationMethod();
myobject.display();
}
}
© 2020 Dr. Ashraf Armoush , An-Najah National University 39

Private Constructor (cont.)


Sharing Initialization Code in Constructors
• One common use of a private constructor is
sharing initialization code among a class’s
other constructors

© 2020 Dr. Ashraf Armoush , An-Najah National University 40


Module ( Java SE 9 )
• “A module is a set of packages designed for reuse”
• Java SE 8 or earlier systems have following problems
– As JDK is too big, it is a bit tough to scale down to small devices.
– JAR files too big to use in small devices and applications.
– As JDK, JRE is too big:
• our applications or devices are not able to support better
Performance.
• it is hard to Test and Maintain applications.
– There is no Strong Encapsulation in the current Java System.
“public” access modifier is too open.
• Everyone can access it.
• They are not to avoid the accessing of some Internal Non-Critical
APIs
• As User can access Internal APIs too:
– Security is also big issue.
– Application is too big.
• Its a bit tough to support Less Coupling between components.

© 2020 Dr. Ashraf Armoush , An-Najah National University 41

Module ( cont.)
• Java SE 9 Module System provides the following
benefits:
– It divides JDK, JRE, JARs etc, into smaller modules, we can use
whatever modules we want.
• So it is very easy to scale down the Java Application to Small
devices.
– Ease of Testing and Maintainability.
– Supports better Performance.
– As public is not just public, it supports very Strong
Encapsulation.
– We cannot access Internal Non-Critical APIs anymore.
– Modules can hide unwanted and internal details very safely, we
can get better Security.
– Application is too small because we can use only what ever
modules we want.
– Its easy to support Less Coupling between components

© 2020 Dr. Ashraf Armoush , An-Najah National University 42


Module ( cont.)
• What is Java 9 Module?
– A Module is a self-describing collection of Code, Data, and
some Resources.
– It is a set of related Packages, Types (classes, abstract
classes, interfaces etc) with Code & Data and Resources.
– Each Module contains only a set of related code and data to
support Single Responsibility (Functionality) Principle (SRP).
Java 9 Module

Data + Resources
Code
Module Descriptor
module-info.java

© 2020 Dr. Ashraf Armoush , An-Najah National University 43

Module ( cont.)
• Java 8 Vs. Java 9 Application
Java 8 Application Java 9 Application

Module Module Descriptor


Packages
Packages
Types (Classes, Abstract Classes,
Types (Classes, Abstract Classes,
Interfaces, …)
Interfaces, …)
Resources
Resources
● XML
Code Data ● XML
● Properties Code Data
● Properties
● etc.
● etc.

© 2020 Dr. Ashraf Armoush , An-Najah National University 44


Module ( cont.)
• Oracle Corp has separated JDK jars and Java SE Specifications
into two set of Modules.
– All JDK Modules starts with “jdk.*”
– All Java SE Specifications Modules starts with “java.*”
• We have two types of packages in a module:
– Exported Packages: These packages are intended to be used outside
of the module, which means any program residing in any other
module can use these packages.
– Concealed Packages: These packages are internal to the module and
can be used inside the module only.

• In java we define the module in module-info.java file and


to mention any package as exported packages we mention the
name of package after exports keyword
© 2020 Dr. Ashraf Armoush , An-Najah National University 45

Module ( cont.)
• Ex: Java 9 Module System has a “java.base”
Module.
– It’s known as Base Module.
– It’s the foundation of every java program.
– It’s an Independent module and does NOT depend on
any other modules.
– By default, all other Modules are dependent on this
module.
– Module is also known as The Mother of Java 9
Modules.
– It’s default module for all JDK Modules and User-
Defined Modules.

© 2020 Dr. Ashraf Armoush , An-Najah National University 46


Module ( cont.)

// module-info.java
module java.base {
exports java.lang;
exports java.io;
exports java.net;
exports java.util;
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 47

Module ( cont.)
Accessibility (JDK 1-JDK8) Accessibility (JDK 9)

• public • public to everyone

• protected • public but only to friend


modules
• package
• public only within a module
• private
• protected

• package

• private

© 2020 Dr. Ashraf Armoush , An-Najah National University 48


Module ( cont.)
• Module Declarations:
– A module must provide a module descriptor—metadata that
specifies:
• the module’s dependencies
• the packages the module makes available to other modules
• and more.
– A module descriptor is the compiled version of a module
declaration that’s defined in a file named module-info.java.
– Each module declaration begins with the keyword module
module modulename {

– The module declaration’s body can be empty or may contain


various module directives, including requires, exports, ….
© 2020 Dr. Ashraf Armoush , An-Najah National University 49

Module ( cont.)
• requires module directive specifies that this module
depends on another module—this relationship is called a
module dependency. Each module must explicitly state its
dependencies.
• requires transitive—(implied readability). To specify
a dependency on another module and to ensure that other
modules reading your module also read that dependency
• An exports module directive specifies one of the
module’s packages whose public types (and their nested
public and protected types) should be accessible to code in
all other modules.
• An exports…to directive enables you to specify in a comma-
separated list precisely which module’s or modules’ code
can access the exported package (this is known as a
qualified export.

© 2020 Dr. Ashraf Armoush , An-Najah National University 50


Module ( cont.)

package edu.najah.firstPackage;
HelloModularWorld.java
public class HelloModularWorld {

public static void main(String[] args) {


System.out.println("Hello, modular World!");
}
}

module ch05_Ex_07_ModuleTest {
module-info.java
exports edu.najah.firstPackage;
requires java.base;
// because every Java module needs 'java.base', it is not
// necessary to explicitly require it- I do it nonetheless for
// demo purposes
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 51

Module ( cont.)
• Dependency Graph
com.seal.utils

example.tools

example.conv

© 2020 Dr. Ashraf Armoush , An-Najah National University 52

You might also like