Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 119

Object-Oriented Programming

Chapter 3: OOP Principles


Introduction
The three fundamental object oriented
programming principles are:

Encapsulation (data hiding) and Data


abstraction
Inheritance
Polymorphism

Main purpose of these principles is to manage


software system complexity by improving
Encapsulation
Encapsulation refers to the
..
combining of fields and methods
together in a class such that the

M
methods operate on the data, as M Class

2
1
opposed to users of the class
accessing the fields directly. Fields/Data
It is a the technique which
involves making the fields in a M
4

M3
class private and providing
access to the fields via public
methods.
Encapsulation
If a field is declared private, it cannot be accessed by
anyone outside the class, thereby hiding the fields
within the class.
For this reason, encapsulation is also referred to as
data hiding.
Encapsulation can be described as a protective barrier
that prevents the code and data being randomly
accessed by other code defined outside the class.
The main benefit of encapsulation is the ability to
modify our implemented code without breaking the
code of others who use our code.
Encapsulation Example
public class EncapTest{ public void setAge( int newAge){
private String name; age = newAge;
private String idNum; }
private int age; public void setName(String
public int getAge(){ newName){
return age; name = newName;
} }
public String public void setIdNum( String newId)
getName(){ {
return name; idNum = newId;
} }
public String }
getIdNum(){
return idNum;
}
Encapsulation, example
The public methods are the access points to this class’s fields
from the outside java world.
Normally these methods are referred as getters and setters.
Therefore any class that wants to access the variables should
access them through these getters and setters.
The variables of the EncapTest class can be accessed as below:
public class RunEncap{
Out Put:
public static void main(String args[]){
Name : James Age : 20
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+ " Age : "+
encap.getAge());
}
}
Data Abstraction
 Classes normally hide the
details of their
implementation from their
clients.
 This is called information
hiding.
 The client cares about what
functionality a class offers,
not about how that
functionality is implemented.
 This concept is referred to as
data abstraction.
Inheritance
Object-oriented programming (OOP): allows you to
derive new classes from existing classes. This is called
inheritance.

In other words, Inheritance is a way to form new


classes using classes that have already been defined.

A class C1 extended from another class C2 is called a


subclass, and C2 is called a superclass. A superclass is
also refered to as a supertype, a parent class, or a base
class and subclass as subtype, a child class, an extended
class, or derived class.
Inheritance
A subclass
 may inherit accessible data fields and methods
from its superclass (the immediate parent and all
its Ancestors)
 may add new data fields and methods.
 may also override an inherited method by
providing its own version, or hide an inherited
variable by defining a variable of the same
 Sometimes it is necessary for the subclass to
modify the implementation of a method defined in
Inheritance

Inheritance is employed to help reuse existing code


with little or no modification.

The inheritance relationship of subclasses and


superclasses gives rise to a hierarchy.

With the use of inheritance the information is made


manageable in a hierarchical order.
Inheritance

Inheritance Hierarchy for Shapes


Inheritance…
Elements to be inherited from parent class are
protected and public members.

Private members of the superclass are not inherited by


the subclass and can only be indirectly accessed.

Members that have default accessibility in the


superclass are also not inherited by subclasses in other
packages.
These members are only accessible by their simple
names in subclasses within the same package as the
superclass.
Inheritance

Elements to be inherited form parent class:


Attributes

 protected Members
Methods

Attributes

 Public Members

Methods
Inheritance…

An instance method can be overridden only if it is


accessible.

Thus a private method cannot be overridden,


because it is not accessible outside its own class.

If a method defined in a subclass is private in its


superclass, the two methods are completely
unrelated.
Inheritance…
Applications of inheritance
Specialization
The new class or object has data or behavior
aspects that are not part of the inherited class.
Overriding
Permit a class or object to replace the
implementation of an aspect—typically a behavior
—that it has inherited
Code re-use
Re-use of code which already existed in another
class.
Inheritance…

In Java inheritance is represented by the key word

extends.
Syntax
modifier class SubclassName extends SuperclassName
{
//body
}

Example
public class Mammal extends Animal
{
//body
}
Inheritance…
The inheritance relationship is transitive: if class x
extends class y, then a class z, which extends class x,
will also inherit from class y.
public class Animal{ …}
public class Mammal extends Animal{…}
public class Reptile extends Animal{…}
public class Dog extends Mammal{…}
Inheritance …
Now based on the above example, In Object Oriented
terms following are true:
Animal is the superclass of Mammal and Reptile classes.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes.

A very important fact to remember is that Java only


supports only single inheritance. This means that a class
cannot extend more than one class. Therefore the following
is illegal:
public class Dog extends Animal,
Mammal{…}
Inheritance…
public class Student {
protected String name;

public Student() {
name = “”;
}
public Student(String s) {
name = s;
}
public String getName(){
return name;
}
}

Note: Object is the super class of all Java Classes.


Inheritance…

The instanceof operator compares an object to a


specified type.

You can use it to test if an object is an instance of a


class, an instance of a subclass, or an instance of a
class that implements a particular interface.
Inheritance…
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce following


result:
true
true
Inheritance Example

class Animal {
public int numberOfLegs;
public void talk() {
System.out.println("Hello");
}
}
Inheritance Example…
class Dog extends Animal {
public int numberOfFleas;
public Dog() {
numberOfLegs = 4;
numberOfFleas = 10;
}
public void bark() {
System.out.println("Woof woof");
}
public void scratch() {
if (numberOfFleas > 0) numberOfFleas--;
}
}
Inheritance Example…
Dog d=new Dog();
d.bark();
d.scratch();
System.out.println(d.numberOfFleas);

Because the Dog class inherits from the Animal class,


we can also use the d reference to access the methods
and properties of the Animal class. Use the code
below.

d.talk();
System.out.println(d.numberOfLegs);
Super keyword
When extending a class you can reuse the
immediate superclass constructor and overridden
superclass methods by using the reserved word
super.

The keyword super refers to the superclass of the


class in which super appears. This keyword can be
used in three ways:
 To call a superclass method
 To call a superclass constructor
 To access a hidden data fields
Super keyword…

 Unlike data fields and methods, a superclass's


constructors are not inherited in the subclass.
 They can only be invoked from the subclasses'
constructors, using the keyword super.

 If the keyword super is not explicitly used, the


superclass‘s no-arg constructor is automatically
invoked.
Super keyword

 You must use the keyword super to call the


superclass constructor.

 Invoking a superclass constructor’s name in a


subclass causes a syntax error.

 Java requires that the statement that uses the


keyword super appear first in the constructor.
Super keyword
Example
class A{
public int a, b, c;
public A(int p, int q, int r){
a=p;
b=q;
c=r;
}
public void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}// end of class A
Example…
public class B extends A{
public int d;
public B(int l, int m, int n, int p){ Output
super(l, m, n); a=4
d=p; b=3
} c=8
public void Show(){ d=7
super.show()
System.out.println("d = " + d);
}
public static void main(String args[]){
B b = new B(4,3,8,7);
b.Show();
}
}//end of class B
Constructor Chaining
A constructor may invoke an overloaded constructor or
its superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first
statement in the constructor. For example,

public A() { is equivalent to public A() {


} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}

30
Constructor Chaining

 Constructing an instance of a class invokes all the


superclasses’ constructors along the inheritance
chain. This is called Constructor Chaining.
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
//*********************************************************************
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
//
************************************************************************
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

32
animation

public class Faculty extends Employee {


public static void main(String[] args) {
new Faculty(); Start from the
} main method
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
33
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
Invoke Faculty
public Faculty() {
constructor
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

34
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
Invoke Employee’s no-
class Employee extends Person {
public Employee() { arg constructor
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

35
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
Invoke Employee(String)
class Employee extends Person { constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

36
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
Invoke Employee(String)
class Employee extends Person { constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

37
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person { Invoke Person()


public Person() { constructor
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

38
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() { Execute println
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

39
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
40
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() { Execute println
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

41
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person { Execute println


public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

42
Inheritance Example
Inheritance Example…
Inheritance Example…
Inheritance Example…
Super keyword….
You can also use super to refer to a hidden field.

Within a class, a field that has the same name as a


field in the superclass hides the superclass's field,
even if their types are different.
Within the subclass, the field in the superclass cannot
be referenced by its simple name. Instead, the field must
be accessed through super.

Generally speaking, we don't recommend hiding fields


as it makes code difficult to read.
Super keyword….

 You cannot override final methods, methods in


final classes, private methods or static methods
Writing Final Classes and Methods…
We may want to prevent classes from being
extended. In such case , use the final modifier to
indicate that a class is final and cannot be a parent
class.

A final class cannot be extended. This is done for


reasons of security and efficiency. Accordingly,
many of the Java standard library classes are final,

Example:
java.lang.System, java.lang.Math
and java.lang.String.
Writing Final Classes and Methods…
A final method cannot be overriden by subclasses.
This is used to prevent unexpected behavior from a
subclass altering a method that may be crucial to the
function or consistency of the class.
You might wish to make a method final if the
method has an implementation that should not be
changed.
 All methods in a final class are implicitly final.

The Object class does this—a number of its methods


are final.
Abstract classes and methods
Abstract classes are like regular classes with data and
methods, but we cannot create instance of abstract
classes using the new operator.
An abstract class is one that cannot be instantiated.

Classes that can be instantiated are known as concrete


classes.
If a class is abstract and cannot be instantiated, the
class does not have much use unless it is subclassed.
This is typically how abstract classes come about
during the design phase.
Abstract classes and methods
Use the abstract keyword to declare a class abstract.
The keyword appears in the class declaration
somewhere before the class keyword.
Abstraction Example
public abstract class Employee{
private String name, address;
private int number;
public Employee(String name, String address, int number){
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay(){
System.out.println("Inside Employee computePay");
return 0.0;
}
Abstraction Example…
public void mailCheck(){
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing a check to " + name + " "
+ address);
}
public String toString(){
return name + " " + address + " " + number;}
public String getName(){
return name;}
public String getAddress() { return address; }
public void setAddress(String newAddress){ address =
newAddress;}
public int getNumber(){ return number;
}
}// end of class Employee
Abstraction Example…

When you would compile, using instances of Employee


class, above class then you would get following error:
Employee is abstract; cannot be instantiated
Abstraction Example… extending
public class Salary extends Employee {

private double salary; //Annual salary


public Salary(String name, String address, int number, double salary){
super(name, address, number);
setSalary(salary);
}
public void mailCheck(){
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName() + " with salary
"+
salary);
}
Abstraction Example… extending
public double getSalary(){ return salary; }
public void setSalary(double newSalary){
if(newSalary >= 0.0){
salary = newSalary;
}
}
public double computePay(){
System.out.println("Computing salary pay for " +
getName());
return salary/52;
}
}
Abstraction Example…
Here we cannot instantiate a new Employee, but if we
instantiate a new Salary object, the Salary object will
inherit the three fields and seven methods from
Employee.
public class AbstractDemo{
public static void main(String [] args) {
Salary s = new Salary("Mohd ", "Ambehta, UP“, 3, 3600.00);
Salary e = new Salary("John ", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}
Abstraction Example…
This would produce following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary
3600.0

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.
Abstract classes and methods

If you want a class to contain a particular method but


you want the actual implementation of that method to
be determined by child classes, you can declare the
method in the parent class as abstract.
The abstract keyword is also used to declare a
method as abstract.
An abstract methods consist of a method signature,
but no method body - its signature is followed by a
semicolon, not curly braces as usual.
Abstraction Example…
An Abstract Class Example

In an object-oriented drawing application, you can draw


circles, rectangles, lines, Bezier curves, and many other
graphic objects.

These objects all have certain states (for example: position,


orientation, line color, fill color) and behaviors (for
example: moveTo, rotate, resize, draw) in common.

Some of these states and behaviors are the same for all
graphic objects—for example: position, fill color, and
moveTo.
Abstraction Example…
An Abstract Class Example

Others require different implementations—for


example, resize or draw.

 All GraphicObjects must know how to draw or


resize themselves; they just differ in how they do
it.
This is a perfect situation for an abstract superclass.
Abstraction Example…
An Abstract Class Example
The GraphicObject class can look something like this:

abstract class GraphicObject {


int x, y;
...
void moveTo(int newX, int newY){...}
abstract void draw();
abstract void resize();
}
Abstraction Example…
An Abstract Class Example
Each non-abstract subclass of GraphicObject, such as
Circle and Rectangle, must provide implementations for the
draw and resize methods:
class Circle extends GraphicObject {
void draw(){... }
void resize(){...}
}
class Rectangle extends GraphicObject {
void draw(){...}
void resize(){...}
}
Abstract classes and Methods
Abstract classes contain mixture of non-abstract and
abstract methods.
 static, private, and final methods cannot be abstract,
since these types of methods cannot be overridden by
a subclass.
Similarly, a final class cannot contain any abstract
methods.
Abstract classes and Methods
Declaring a method as abstract has two results:

The class must also be declared abstract. If a class


contains an abstract method, the class must be
abstract as well.

When an abstract class is subclassed, 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.
Abstraction of method Example
public abstract class Employee{
private String name, address;
private int number;
public abstract double computePay();
…//remainder of the class definition
}
public class Salary extends Employee{
private double salary; //Annual salary
public double computePay(){
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
…//remainder of the class defiition
}
Interfaces
Interfaces are similar to abstract classes but all
methods are abstract and all data fields are static
final.
That is an interface is a collection of abstract
methods and static final variables.
An interface is not a class. Writing an interface is
similar to writing a class, but they are two different
concepts.
A class describes the attributes and behaviors of an
object. An interface contains behaviors that a class
Interfaces
Interfaces have the following properties:

An interface is implicitly abstract. You do not need


to use the abstract keyword when declaring an
interface.
Each method in an interface is also implicitly
abstract, so the abstract keyword is not needed.
Methods in an interface are implicitly public.
Interfaces…
Interfaces can be inherited (i.e. you can have a
sub-interface). As with classes the extends
keyword is used for inheritance.
A class implements an interface, thereby inheriting
the abstract methods of the interface.
Unless the class that implements the interface is
abstract, all the methods of the interface need to be
defined in the class.
A concrete class may implement one or several
interfaces, supplying the code for all the methods.
Interfaces…
An interface is similar to a class in the following
ways:

 An interface can contain any number of methods.


 An interface is written in a file with a .java
extension, with the name of the interface
matching the name of the file.
 The bytecode of an interface appears in a .class
file.
 Interfaces appear in packages, and their
corresponding bytecode file must be in a
Interfaces…
However, an interface is different from a class in several
ways, including:
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields.
An interface is not extended by a class; it is implemented
by a class.
An interface can extend multiple interfaces.
Declaring Interfaces
The interface keyword is used to declare an interface.

public interface NameOfInterface


{
//Any number of final, static fields
//Any number of abstract method declarations\
}
Implementing Interfaces
A class uses the implements keyword to implement an
interface.
The implements keyword appears in the class
declaration following the extends portion of the
declaration.

interface Animal {
public void eat();
public void travel();
}
Implementing Interfaces
public class Mammal implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels"); }
public int noOfLegs(){
return 0; }
public static void main(String args[]){ Output:
Mammal m = new Mammal(); Mammal eats
m.eat(); Mammal travels
m.travel();
}
}
Extending Interfaces
An interface can extend another interface, similarly to the
way that a class can extend another class.
The extends keyword is used to extend an interface, and the
child interface inherits the methods of the parent interface.
public interface Sports{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
public interface Football extends Sports{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
Extending Interfaces…
public interface Hockey extends Sports{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from
Sports; thus, a class that implements Hockey needs to implement
all six methods.
Similarly, a class that implements Football needs to define the
three methods from Football and the two methods from Sports.
Note that an interface can extend more than one parent interface
public interface Hockey extends Sports, Event
Inheritance (cont’d)
subclass superclass
or extends or
derived class base class

subinterface extends superinterface

class implements interface

78
Inheritance (cont’d)
In Java, a subclass can extend only one superclass.
In Java, a subinterface can extend several
superinterface
In Java, a class can implement several interfaces —
this is Java’s form of multiple inheritance.

79
Inheritance (cont’d)
An abstract class can have code for some of its
methods; other methods are declared abstract
and left with no code.
An interface only lists methods but does not
have any code.

80
Inheritance (cont’d)
Inheritance plays a dual role:
A subclass reuses the code from the superclass.
A subclass (or a class that implements an interface)
inherits the data type of the superclass (or the
interface) as its own secondary type.

81
Abstrac vs Interface
Unlike interfaces, abstract classes can contain fields
that are not static and final, and they can contain
implemented methods.

If an abstract class contains only abstract method


declarations, it should be declared as an interface
instead.

Multiple interfaces can be implemented by classes


anywhere in the class hierarchy, whether or not they
are related to one another in any way.
Abstract vs. Interface

By comparison, abstract classes are most commonly


subclassed to share pieces of implementation.

A single abstract class is subclassed by similar classes


that have a lot in common (the implemented parts of
the abstract class), but also have some differences (the
abstract methods).
Polymorphism
The inheritance relationship enables a subclass to
inherit features from its superclass with additional new
features.
A subclass is a specialization of its superclass.

Every instance of a subclass is an instance of its


superclass, but not vice versa.
A subclass possesses all the attributes and operations
of its superclass (because a subclass inherited all
attributes and operations from its superclass).
This means that a subclass object can do whatever
its superclass can do.
Polymorphism
Polymorphism (from the Greek, meaning “many
forms”) is the ability of an object to take on many
forms.
All interaction with an object occurs through object
reference variables.
An object reference variable holds the reference
(address, the location) of an object.
An object reference can refer to an object of its class,
or to an object of any class derived from it by
inheritance.
Polymorphism
For example, if the Holiday class is used to
derive a child class called Christmas, then a
Holiday reference could actually be used to
point to a Christmas object.
For example,
Holiday
Holiday day;
day = new Holiday();
Christmas …
day = new Christmas();

The assignment of an object of a derived class to


a reference variable of the base class can be
86
considered as a widening conversion
Polymorphism
class Holiday
{
public void celebrate()
{…}
}
//************************

class Christmas extends Holiday


{
public void celebrate()
{…}
public void listenToChristmasSongs()
{…}
}

Can we do the following statements?


Holiday day;
day = new Christmas(); day.celebrate();
day.listenToChristmasSongs();
87
Polymorphism
The most common use of polymorphism in OOP
occurs when a parent class reference is used to refer to
a child class object.
A reference variable can be of only one type. Once
declared the type of a reference variable cannot be
changed.
The reference variable can be reassigned to other
objects provided that it is not declared final.
 The type of the reference variable would determine
the methods that it can invoke on the object.
A reference variable can refer to any object of its
Polymorphism example

public class Shape{


public double computeArea(){
return -1;
}
public double computeCircumfrence(){
return -1;
}
}
Polymorphism example

public class Circle extends Shape{


private double radius;
public Circle(double r){
this.radius = r;
}
public double computeArea(){
return Math.PI*this.radius * this.radius;
}
public double computeCircumfrence(){
return 2*Math.PI*this.radius;
}
}
Polymorphism example…
public class Rectangle extends Shape{
private double width;
private double height;
public Rectangle(double w, double h){
this.width = 0;
this.height = 0;
}
public double computeArea(){
return this.width * this.height;
}
public double computeCircum(){
return 2*(this.width *this.height);
}
}
Polymorphism example…
public class ShapeTest{
public static void main(String args[]){
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(4.0);
shapes[1] = new Rectangle(5, 3);
shapes[2] = new Circle(1.8);
double totalArea = 0;
for(int i = 0;i<shapes.length;i++){
totalArea+=shapes[i].computeArea();
}
System.out.println(“Total area = “ +totalArea);
}
}
Polymorphism example

Out Put: Total area = 60.44424265506762

A reference variable of type Shape is used to refer


objects of types of its subclasses (Circle and rectangle)

What is the output of the above code if you comment


out computeArea() method in Circle and
Rectangle classes?

Out Put: Total area = -3.0


Polymorphism…
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. (See the example on shapes).

Suppose an object o is an instance of class c1,c2, ….cn-1 and


cn, where c1 is subclass of c2, c2 is 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 m ,the JVM searches the


implementation for m in c1,c2,…cn-1 and cn in this order, until
it is found.
Polymorphism…
The output illustrates that the appropriate methods for
each class are indeed invoked based on the type of the
object to which shapes refers.
This is called dynamic binding or late binding.
However, if a program needs to perform a subclass-
specific operation on a subclass object referenced by a
superclass variable, the program must first cast the
superclass reference to a subclass reference through a
technique known as downcasting.
This enables the program to invoke subclass methods
that are not in the superclass.
Polymorphism…
Upcasting & Downcasting
Substituting a subclass instance for its superclass is
called "upcasting".
Upcasting is always safe because a subclass instance
possesses all the properties of its superclass and can do
whatever its superclass can do.
You can revert a substituted reference back to the
original subclass. This is called "downcasting".
 For example,
Shape shape = new Circle(5.0);// upcast is safe
Circle aCircle = (Circle)shape;
//downcast needs the casting operator
Polymorphism …
For Example if a Rectangle class had
getDiagonal() method and if we want to use this
method we must first downcast it.
if(shap[1] instanceOf Rectangle)
Rectangle r = (Rectangle)shapes[1];
We cannot treat a superclass object as a subclass object
because a superclass object is not an object of any of its
subclasses.
Polymorphism…
Assigning a superclass variable to a subclass variable
(without an explicit cast) is a compilation error.

Downcasting requires explicit type casting operator in


the form of prefix operator (new‐type).
Downcasting is not always safe, and throws a runtime
ClassCastException if the instance to be downcasted
does not belong to the correct subclass.
A subclass object can be substituted for its superclass,
but the reverse is not always true.
Polymorphism …
It is possible to display each shape’s type as a string.
for(int i = 0;i<shapes.length;i++){
System.out.printf( “Shape %d is a %s\n", i,

shapes[ i].getClass().getName());
}
The output is
Shape 0 is a Circle
Shape 1 is a Rectangle
Shape 2 is a Circle
Polymorphism…
Polymorphism can also be achieved through method
overriding and method overloading.
Overridden methods
 Are methods that are redefined within an inherited or
subclass. They have the same signature and the
subclass definition is used.
The implementation in the subclass overrides
(replaces) the implementation in the superclass.
In other words an instance method in a subclass with
the same signature (name, plus the number and the type
of its parameters) and return type as an instance method
in the superclass overrides the superclass's method.
Method overriding example
class Rectangle {
private int x, y, w, h;
public String toString() {
return “x = “ + x + “, y = “ + y +“, w = “ + w + “, h = “ + h;
}
}
class DecoratedRectangle extends Rectangle {
private int borderWidth;
public String toString() {
return super.toString() + “, borderWidth = “ + borderWidth;
}
}
Method overriding Rules
The argument list should be exactly the same as that of
the overridden method.
The return type should be the same or a subtype of the
return type declared in the original overridden method in
the super class.
The access level cannot be more restrictive than the
overridden method's access level.
For example: if the super class method is declared
public then the overriding method in the subclass
cannot be either private or protected.
Method overriding Rules
However the access level can be less restrictive than the
overridden method's access level.
Instance methods can be overridden only if they are
inherited by the subclass.
Constructors cannot be overridden.
A method declared final cannot be overridden.
A method declared static cannot be overridden but
can be re-declared.
If a method cannot be inherited then it cannot be
overridden.
Method overriding Rules…
A subclass within the same package as superclass
can override any superclass method that is not
declared private or final.
A subclass in a different package can only override
the non-final methods declared public or protected.
Polymorphism…
Method Overloading
Overloaded methods are methods with the same name
signature but either a different number of parameters or
different types in the parameter list.
Compiler automatically select the most appropriate
method based on the parameter supplied.
Example
public class MultiplyNumbers {
public int Multiply(int a, int b) {
return a * b;
}
public int Multiply(int a, int b, int c) {
return a*b*c;
}
}
Package
A Package (named collections of classes) can be defined
as a grouping of related types(classes and interfaces)
providing access protection and name space management.

Packages are used in Java in-order to prevent naming


conflicts, to control access, to make searching/locating
and usage of classes, interfaces, enumerations and
annotations easier etc.

Java has numerous built in packages: java.io, java.lang,


java.util …
Package

Programmers can define their own packages to bundle


group of classes/interfaces etc.
It is a good practice to group related classes
implemented by you so that a programmers can easily
determine that the classes, interfaces, enumerations,
annotations are related.
Creating a package
When creating a package, you should choose a name
for the package and put a package statement with that
name at the top of every source file that contains the
classes and interfaces types that you want to include in
the package.
The package statement should be the first line in the
source file.

There can be only one package statement in each


source file, and it applies to all types in the file.
Creating a package
It is common practice to use lowercased names of
packages to avoid any conflicts with the names of
classes, interfaces.
If a class wants to use another class in the same
package, the package name does not need to be used.
Classes in the same package find each other without
any special syntax.
A class file can contain any number of import
statements.
The import statements must appear after the package
statement and before the class declaration.
Let us look at an example that creates a package called
Creating a package…Example
package animals;
interface Animal {
public void eat();
public void travel();
}
//-------------------------------------------------------------------------
-
package animals;
public class MammalInt implements Animal{
public void eat(){ System.out.println("Mammal eats"); }
public void travel(){ System.out.println("Mammal
travels"); }
Creating a package…Example
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Now you compile these two files and put them in a sub-
directory called animals and try to run as follows:
$ mkdir animals
$ cp Animal.class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels
Creating a package…Example
Here a class named Boss is added to the payroll package that
already contains Employee.
The Boss can then refer to the Employee class without using
the payroll prefix, as demonstrated by the following Boss
class.
package payroll;
public class Boss{
public void payEmployee(Employee e) {
e.mailCheck();
}
}
Creating a package…Example
If Boss was not in the payroll package, then use one of
the following techniques for referring to a class in a
different package.
The fully qualified name of the class can be used.
For example: payroll.Employee
The package can be imported using the import keyword
and the wild card (*).
For example: import payroll.*;
The class itself can be imported using the import
keyword.
For example: import payroll.Employee;
Passing objects
Passing by value for primitive type value
the value is passed to the parameter
Passing by value for reference type value
the value is the reference to the object
Example
public class TestPassObject {
public static void main(String[] args) {
int radius =1;
Circle3 myCircle = new Circle3(1);
int n = 5;
printAreas(myCircle, n);
System.out.println("\n" + "Radius is "
+myCircle.getRadius());
System.out.println("n is " + n);
}
Passing objects…
public static void printAreas(Circle3 c, int times) {
System.out.println("Radius \t\tArea");
while (times >= 1) {
System.out.println(c.getRadius() + "\t\t" +
c.getArea()); c.setRadius(c.getRadius() + 1);
times--;
}
}
}
A reference type of Circle3 called c is passed to a
function printAreas()
Returning objects
public class BirthDate{
private int year;
private int month;
private int day;
public BirthDate(int newYear,
int newMonth, int newDay){
year = newYear;
month = newMonth;
day = newDay;
}
public void setYear(int newYear){
year = newYear;
}
}
Returning objects…
public class Student {
private int id;
private BirthDate birthDate;
public Student(int ssn,
int year, int month, int day) {
id = ssn;
birthDate = new BirthDate(year, month, day);
}
public int getId() {
return id;
}
public BirthDate getBirthDate() {
return birthDate;
} BirthDate is
} returned
Returning objects…

public class Test {


public static void main(String[]args{
Student student = new
Student(111223333, 1970, 5, 3);
BirthDate date =
student.getBirthDate();
date.setYear(2010);
// Now the student birth year is changed!
}
}
Q&A

You might also like