OOP Principles (Polymorphism, Abstraction)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

CHAPTER Two –

Polymorphism
What Do you think about this Concept

✓ Introduction
✓ superclass reference to subclass-type variable
✓ subclass method calls via superclass type variable
✓ Multiple inheritance and interfaces
Introduction
✓ Polymorphism allows programmers to send the same message to
objects from different classes.
✓ Polymorphism enables us to “program in the general” rather than
“program in the specific”.
✓ Polymorphism enables you to write programs that process objects that
share the same superclass (either directly or indirectly) as if they are all
objects of the super class.
✓ It is possible to design and implement systems that are easily
extensible. i.e., new class can be added with little or no modification to
the general portion of the program.
R/Ship among Objects in Inheritance
✓ An object of subclass can be treated as object of its superclass.
✓ A Program can create an array of superclass reference that refers to
objects of many subclass types.
✓ This is allowed because a subclass is a type of its superclass.
✓ However, we can’t treat a superclass object as a subclass object
because a superclass object is not an object of any of its subclasses.
The “is-a” relationship applies only from a subclass to its direct and
indirect superclass.

N.B The java compiler will allow the assignment of a superclass


reference to a subclass variable if we explicitly cast the super class
reference to the subclass type.
❖ Assigning reference of a subclass to a superclass-type variable
E.g.
public class Point3{ ……………………

private int x; public void setX (int xValue){

private int y; x=xValue; }

public Point3() public void setY(int yValue) {

{ y=yValue; }

} public int getX(){

public Point3(int xValue, int yValue) return x; }

{ public int getY() {

x=xValue; return y; }

y=yValue; public String toString() {

} return “[“+getX()+ “, ”+getY()+ “]”; }

}//end class
public class Circle4 extends Point3 {
public class PolyTest{
private double radius;
public static void main(String args[])
public Circle4(int xValue, int yValue, double rValue) {
{
super(xValue,yValue);
Point3 point = new Point3(30,50);
setRadius(rValue); }
Circle4 circle = new Circle4(120,89,2.7);
public void setRadius(double rValue) {
String output = “Call Point3’s toString with superclass”+
radius = (rValue < 0.0?0.0:rValue); }
“reference to superclass object:\n”+ point.toString();
public double getRadius() {
output+= “\n\nCall Circle4’s toString with subclass
return radius; }
”+ “reference to subclass object:\n”+circle.toString();
public double getDiameter() {
Point3 pointRef = circle;
return 2*getRadius(); }
Output+= “\n\ncall Circle4’s toString with superclass ”+
public double getCircumfrence() {
“ refernce to subclass object:\n “+pointRef.toString();
return Math.PI*getDiameter(); }

public double getArea() {

return Math.PI*getRadius()*getRadius(); }

public String toString() {

return “Center = “+super.toString()+ “;


Radius=”+getRadius(); }} // end class

}//end class
✓ In the above program, the Statement Point3 pointRef = circle; assigns
the reference of subclass object circle to superclass-type variable
PointRef.
✓ A superclass-type variable that contains a reference to a subclass
object calls the subclass method.
✓ Hence, pointRef.toString() actually calls class Circle4’s toString method
❖ Assigning a superclass object’s reference to a subclass-type
variable
public class PolyTest2{

public static void main(String args[]) {

Point3 point = new Point3(30,50);

Circle4 circle;//subclass-type variable

//assign superclass reference to subclass-type variable


circle = point;

} } // end class

}//end classoutput+= “\n\nCall Circle4’s toString with


subclass

”+ “reference to subclass object:\n”+circle.toString();


✓ If you run this program, it will generate error. Because the assignment is
not allowed (incompatible types). i.e., Compile time error
✓ Point3 is not a Circle4- the “is-a” r/ship applies only between the
subclass and its superclass.
✓ But this kind of assignment works if explicitly cast the superclass
reference to the subclass type.
public class PolyTest2{

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

Point3 point = new Point3(30,50);

Circle4 circle;//subclass-type variable

//assign superclass reference to subclass-type variable


circle = (Circle4) point;

} } // end class

}//end classoutput+= “\n\nCall Circle4’s toString with


subclass

”+ “reference to subclass object:\n”+circle.toString();

Point3 pointRef = circle;

Output+= “\n\ncall Circle4’s toString with superclass ”+


❖ Subclass Method calls via superclass-type
✓ Using Superclass reference, we can only invoke superclass only methods.
✓ Using superclass reference, we can’t Point3 point;
invoke subclass only methods. Circle circle = new Circle4(120,89,2.7);
✓ You can call a method on an object point = circle;//aim superclass reference at subclass object.

only if the class of the reference int x = point.getX();

variable has that method. int y = point.getY();

point.setX(10);

point.setY(20);
✓ When we try to invoke subclass only
point.toString();
methods using point, the java
compiler generates errors on each //attempt to invoke subclass-only (Circle4) method on subclass object through
method. superclass (Point3) reference

✓ Point3 variable can only invoke getX, double radius = point.getRadius();


getY, setX, setY and toString.
point.setRadius(33.33);

double diameter = point.getDiameter();


N.B. The compiler decides whether you
can call a method based on the double circumference = point.getCircumfrence();
reference type, not the actual object double radius = point.getRadius();
type.
}}// end class
Allowed Assignments b/n Super & Sub Class
❖ Assigning a superclass reference to a superclass-type variable is
straight forward
❖ Assigning a subclass reference to a subclass-type variable is
straight forward.
❖ Assigning a subclass object’s reference to a superclass type
variable is safe, because the subclass object is an object of its
superclass.
However, this reference can be used to invoke only superclass methods. If
this code refers to subclass-only members through the superclass variable,
the compiler generates an error.

❖ Attempting to assign a superclass object’s reference to a subclass


type variable is a compile-time error. To avoid the error, the
superclass reference must be cast to a subclass type explicitly.
Abstract Class and Methods
✓ You can’t directly create an instance of an abstract class because
abstract classes are incomplete.
✓ They are used only as super classes in inheritance hierarchies.
❖ Purpose of Abstract Class
✓ Provide an appropriate superclass from which other classes can
inherit and thus share a common design.
For e.g., The shape class can define the notions to be a Shape-
Attributes: location, color and border Thickness

Behaviours: draw,move,resize and ChangeColor.

Subclass inherit and provide implementation of the method defined to be


concrete classes.
✓ Abstract classes are too general to create real objects, they specify
only what is common among subclasses.
E.g., What looks like Animal Object? What shape is it? What color,
size, no of legs etc.…., Such types of class should not be instantiated.

❖ Declaring an Abstract Class


✓ Making a class abstract is easy- put the keyword abstract before the
class declaration.
abstract class Animal {
}
✓ An abstract class normally contains one or more abstract methods but
can include non-abstract method.
✓ Abstract methods can be defined only in abstract classes. If you
attempt to do otherwise, you will be issued a compiler error.
✓ Methods marked with abstract are pure protocol. They simply define
the name, return type (if any), and parameter set (if required).
✓ An abstract method has no body(implementation)!
✓ You can’t think any generic implementation that could possibly be
useful for subclasses.
E.g., What would a generic eat () method look like?

public abstract void eat (); no curly braces – just end the declaration
with semi colon

✓ Here, the abstract Animal class informs the derived types that “I have
a method name eat () that takes no argument and returns nothing. If
you derive from me, you figure out the details”.
✓ Implementing an abstract method is just like overriding a method.
The first class
✓ An abstract class means the class must be extended; an abstract method
means the method must be implemented (provide a body).
✓ When a class extends from Abstract class can’t give any implementation for
the abstract method it should marked as abstract again.
✓ Constructors and static methods can’t be declared abstract.
N.B. Although we can not instantiate objects of abstract super classes, we
can still use that abstract class as a declared reference type, for the
purpose of polymorphism.
Exercise
- Abstract Superclass Employee declares the “interface” to the hierarchy –
set of methods that a program can invoke on all Employee objects.
- Try to create a Polymorphic program by using this information
Multiple Inheritance and Interfaces
✓ An Interface is like a class that can’t be instantiated.
✓ It specifies a set of requirements for a class to implement.
✓ An interface is a description of a capability. It lists the methods that a
class must implement to carry out that capability.
✓ All interface members must be public, and interfaces may not specify
any implementation details, i.e., no instance variables and no default
methods implementations.
✓ A compile-time error occurs if the identifier naming an interface
appears as the name of any other class or interface in the same
package.
✓ All methods declared in an interface are implicitly public abstract
methods and all fields are implicitly public, static and final.
✓ A class that implements an interface must provide an implementation for
all the method signatures in the interface.
✓ An interface specifies what operations are allowed but not how they’re
performed.
✓ A java interface can provide 100% abstraction.
E.g.
public interface Shape {
public double getArea();
public double getVolume();
public String getName();
}
public class Point extends Object implements Shape {
private int x;
private int y;
public Point (int xValue, int yValue)
{
x = xValue;
y = yValue;
}
….
Getter and Setter Methods
public double getArea()
{
return 0.0; }
public double getVolume() {
return 0.0; }
public String getName() {
return “Point”; }
}
✓ When a class implements an interface, the same “is-a” relationship
provided by inheritance applies. For example, class Point implements
Shape. Therefore, a Point object is a Shape. In fact, objects of any class
that extends Point are also Shape objects.
✓ Objects of any subclasses of the class that implements the interface can
also be thought of as objects of the interface type.
✓ Thus, as we can assign the reference of a subclass object to superclass
variable, we can assign the reference of a sub class object to an
interface variable. (Polymorphism)
N.B. By using Interface, unrelated classes can implement a set of common
methods.
You treat an object by the role it plays, rather than by the class type
from which it was instantiated.

Unlike a class, an interface:

❖ Declares only method headers and public constants. i.e. After


java8 it can contain default and static method implementation
❖ Has no Constructors
❖ Can’t be instantiated.
❖ Can be implemented by a class.
❖ Can’t extends a class.
❖ Can extend several other interfaces.
Exercise

Payable Interface
- Contains one method double getPaymentAmount();
It doesn’t contain implementation
Invoice

- Part Number (String)


- Part Description (String)
- Quantity (int)
- pricePerItem (double)
getPaymentAmount() {
return getQuantity() * getPricePerItem();

}
Summary

How do you know whether to make a class, a subclass, an abstract class


or an interface?
❖Make a class that doesn’t extend anything (other than Object). When your
new class doesn’t pass the IS-A Test for any other type.
❖Make a subclass (extend a class) only when you need to make a more
specific version of a class and need to override or add new behaviors.
❖Use an abstract class when you want to define a Template for a group of
subclasses, and you have at least some implementation code that all
subclasses could use. and to guarantee nobody can make object of that
type.
❖Use an Interface when you want to define a role that other classes can play,
regardless of where those classes are in the inheritance tree.
Java API Packages
Java Packages
✓ Java contains many predefined classes that are grouped into categories of
related classes called packages. Together, these are known as the Java
Application Programming Interface (Java API), or the Java class library.
✓ A package is a grouping of related types providing access protection and
name space management. It is like folder in a file directory.
✓ Types refers to classes, interfaces, enums etc.
✓ Packages in java can be categorized in two form, built-in package (Java
API) and user-defined package.
Advantage of Java Package

❖ Used to Categorize the classes and interfaces so that they can be


maintained.
❖ Java package provides access protection.
❖ Java package removes naming collisions.
Built in Packages

✓ Java includes packages for complex graphics, advanced graphical user


interfaces, printing, advanced networking, security, database processing,
multimedia, accessibility (for people with disabilities), concurrent
programming, cryptography, XML processing and many other capabilities.
✓ The library is divided into packages and classes. This means you can either
import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.
✓ To use a class or a package from the library, you need to use the import
keyword.
Syntax: import package.name.Class // import a Single class

import package.name. *; // import the whole package.

Example: import java.util.Scanner;

✓ In this example java.util is a package, while Scanner is a class of the java.util


package.
User-Defined Packages

✓ To create a package, you choose a name for the package and put a
package statement with that name at the top of every source file that
contains the types (classes, interfaces, enumerations, and annotation types)
that you want to include in the package.
//save by A.java //save by B.java
package pack; package mypack;
public class A { import pack.*;
public void msg() {
class B{
System.out.println("Hello");}
} public static void main(String args[]){
A obj = new A();
obj.msg();
}}

✓ Similar with Java Api package we can access our own package.
There are three ways to access the package from outside the package

❖import package.*;
❖import package.classname;
❖fully qualified name;
1) Using packagename. *
✓ If you use package. * then all the classes and interfaces of this package will
be accessible but not sub packages.
✓ The import keyword is used to make the classes and interface of another
package accessible to the current package.
//save by A.java //save by B.java
package pack; package mypack;
public class A{ import pack. *;
public void msg(){ public class B{
System.out.println("Hello");} } public static void main(String args[]){
A obj = new A();
obj.msg(); }}
}
}
2) Using packagename.classname
✓ If you import package.classname then only declared class of this package
will be accessible.

//save by A.java //save by B.java


package pack; package mypack;
public class A{ import pack. A;
public void msg(){ public class B{
System.out.println("Hello");} } public static void main(String args[]){
A obj = new A();
obj.msg(); }}
}
}
3) Using fully qualified name
✓ If you use fully qualified name then only declared class of this package
will be accessible.
✓ There is no need to import.
✓ you need to use fully qualified name every time when you are
accessing the class or interface.

//save by A.java //save by B.java


package pack; package mypack;
public class A{ public class B{
public void msg(){ public static void main(String args[]){
System.out.println("Hello");} } pack.A obj = new pack.A();
obj.msg(); }}
}
}

✓ If you import a package, all the classes and interface of that package will
be imported excluding the classes and interfaces of the sub packages.
Sub packages: Package inside the package is called the sub package. It
should be created to categorize the package further.

Naming Conventions: Package names are written in all lower case to avoid
conflict with the names of class or interface.

You might also like