+ All Categories
Home > Documents > For use of IST410 students only Inheritance-1 Introduction to Inheritance and Polymorphism.

For use of IST410 students only Inheritance-1 Introduction to Inheritance and Polymorphism.

Date post: 20-Dec-2015
Category:
View: 214 times
Download: 0 times
Share this document with a friend
Popular Tags:
47
Inheritance-1 For use of IST410 students only Introduction to Inheritance and Polymorphism
Transcript

Inheritance-1 For use of IST410 students only

Introduction to Inheritance and Polymorphism

Inheritance-2 For use of IST410 students only

Objectives

Concepts of Inheritance Abstract Class Abstract Methods Polymorphism Interfaces

Inheritance-3 For use of IST410 students only

Inheritance

One of the major concepts of OOP is inheritance Through inheritance, code of one class can be reused in

another class The class, whose code is reused, is called base class; also

known as parent or super class The new class that inherits from a base class is known as a

derived class. A derived class may also be called child or subclass

The keyword extends is used to derive a child classclass Child extends Parent { // }

Inheritance-4 For use of IST410 students only

What is inherited?

Parent Methods Data members

Child methods ofParent class+Child classmethods

data members of Parentclass + Child class datamembers

Inheritance-5 For use of IST410 students only

Base class Example

public class Circle { protected double radius; public Circle() { this(1.0); } public Circle(double r) { radius = r; }

public double area() { return radius*radius*Math.PI; }

//other methods of Circle }

since radius has a protected modifier, it can be accessed in a subclass

Suclasses cannot directly access private members of a superclass

Inheritance-6 For use of IST410 students only

subclass Example

public class Cylinder extends Circle { private double length; public Cylinder() { super(); length = 1.0; }

public Cylinder(double r, double l) { super(r); length = l; }

public double volume() { return radius*radius* Math.PI*length; }

//other methods of Cylinder }

radius of the Circle class can be accessed directly in the Cylinder class since it has a protected modifier

Constructors are not inherited

Callsparent class constructor

Inheritance-7 For use of IST410 students only

Modifiers

Java supports 4 modifiers public private protected no modifier

We have examined public and private in earlier discussions protected is used with inheritance A member with a protected modifier is accessible only to

subclasses For example: radius of Circle class is protected and

therefore can be used in a subclass as in the volume method of Cylinder

Inheritance-8 For use of IST410 students only

Modifiers

What if a member is marked private? public class Circle { private double radius; // rest of the class } Direct access of radius in a subclass generates compiler

error public class Cylinder extends Circle {

public double volume() { return radius*radius*Math.PI*length;

}// rest of the class

}Compiler Error

Inheritance-9 For use of IST410 students only

Modifiers

What if a member has no modifier? public class Circle { double radius; // rest of the class } radius is considered to have package visibility What is a package?

A project is often divided into subgroups just like directory Each group may be given an optional package name Each class in the group is then a member of the package Java language itself is divided into a number of packages or

libraries

Inheritance-10 For use of IST410 students only

Inheritance and access level

The table below shows the relationship between the access levels and inheritance

default modifier means no modifierclass MyClass { .... // no modifier }

Base class Modifier Accessible from subclasspublic yesprivate noprotected yesdefault no unless in the same

package

Inheritance-11 For use of IST410 students only

Single Inheritance

Only single inheritance is supported in Java i.e. a subclass can extend only one superclass

Constructs such as class X extends Y, Z { ....} are illegal A protected or public method of the superclass can be

invoked in a subclass method using a super call super.methodName() We will see a partial example later

Inheritance-12 For use of IST410 students only

When do we extend?

Code reuse is not a ‘sufficient’ reason to extend a class A class can be extended when there exists an ‘IS-A’

relationship between two objects Consider two classes: (1) Shape that represents any

geometric shape, and (2) a class called Circle It makes sense to say Circle IS A Shape; therefore, it

would make sense to extend Circle from Shape Does it make sense to say an Automobile is a shape?

Perhaps not. We would not extend Automobile from a class called

Shape

Inheritance-13 For use of IST410 students only

When do we extend?

Automobiles do have shape We may specify an attribute of an automobile using the

Shape classclass AutomobileShape extends Shape { ...... }class Automobile {

AutomobileShape style; //Shape attribute// other implementation details

} There is a relationship between AutomobileShape and

Automobile and it is called HAS-A relationship

Inheritance-14 For use of IST410 students only

Inheritance Hierarchies

We can construct inheritance hierarchies by extending subclasses in succession

For examplepublic class Circle extends Shape { ....... }public class Cylinder extends Circle { ..... }

In the above hierarchy, Cylinder inherits members of Circle as well as those of Shape

More complex inheritance hierarchies can be constructed as shown in the next slide.

Inheritance-15 For use of IST410 students only

Inheritance Hierarchies

Shape

Circle Hexagon Square

Cylinder Cube

Circle inherits from Shape and Cylinder inherits from Circle

Hexagon inherits from Shape and is a sibling of Circle

Square is a sibling of Hexagon and Circle

Cube is a child of Square and has no relationship with Hexagon, Circle, or Cylinder except for common ancestry through Shape

Inheritance-16 For use of IST410 students only

Overriding

Sometimes a specific behavior of the subclass may be different from the corresponding behavior of its parent

For such cases, the method of the superclass can be overridden in the subclass

Consider the area calculation for a Cylinder We may want the area method of a Cylinder to return the

total surface area of the cylinder The area method of Circle, the parent class of Cylinder, is

no more able to do the job for Cylinder and needs to be overriden

Inheritance-17 For use of IST410 students only

Overriding

Area method of the Circle classpublic double area() {

return radius*radius*Math.PI; } The Cylinder class extends Circle

public class Cylinder extends Circle { ...... } The area of a Cylinder is different from that of Circle Choices:

Name the area method of Cylinder: CylinderArea? Name the area method of Cylinder: area? <---- Override

Inheritance-18 For use of IST410 students only

Overriding

area method of the Circle can be overriden by implementing an area method in the Cylinder classpublic double area() { // Cylinder method

double xSection = 2 * Math.PI*radius*radius;double cSurface = 2*Math.PI*radius*length;

return (xSection+ cSurface); } Rules for overriding

return type of both must be the same must have same access level must have same name and argument list

Inheritance-19 For use of IST410 students only

Including parent class method call in subclass methods

Consider the area() method of the Cylinder class again. A part of this method calculates the cross section area of

the cylinder that is nothing more than the area of a circle. We have an area method in the circle class and do not need

to recode this part in the cylinder’s area calculation

public double area() {

double xSection = 2 *super.area();double cSurface = 2*Math.PI*radius*length;

return (xSection+ cSurface); }

Calculation replaced by call to the super class method

Inheritance-20 For use of IST410 students only

Preventing Overriding

Sometimes we would like to prevent overriding A method can be prevented from being overridden by

making it final

public final double area() { // Cylinder method // implementation }

Inheritance-21 For use of IST410 students only

Preventing Inheritance

Sometimes we do not want a class to be subclassed Inheritance can be prevented by making the class final

public final class Cylinder {// implementation

}

Inheritance-22 For use of IST410 students only

Java Inheritance Hierarchy

All classes in Java derive from a class called Object Therefore we could have written

public class Circle extends Object ....public class Cylinder extends Circle ...

Cylinder class not only inherits from Circle, but also from Object

Since all Java classes derive from Object, it is possible to construct collection of Objects

Java language supports such collections through its collection API: Vector, Hashtable, Map, List etc.

Inheritance-23 For use of IST410 students only

Java Inheritance Hierarchy

Two useful methods of Object public String toString()

Returns a String representation of the object’s data If not overriden, method can still be called but would result in

garbage information protected Object clone()

Clones the object on which this method is called Need to override these methods in the class

Inheritance-24 For use of IST410 students only

Memory Allocation

The construction of an object that inherits from another can be conceptually shown as follows

Cylinder cy = new Cylinder();

Object

Circle

Cylinder

Inheritance-25 For use of IST410 students only

Memory Allocation

What happens when we construct an object that inherits from some superclass?

Memory is allocated for the entire object All instance variables are initialized to their default values Starting with the object being created, constructors are called

recursively all the way through Object using the following order Constructor parameters are bound to their values If this() call exists, execute recursively and finish by executing

the body of the current constructor If no this(), call explicit or implicit super() except for Object Execute explicit instance variable initializers Execute the body of the current constructor

Inheritance-26 For use of IST410 students only

Memory Allocation

What happens when we construct a Cylinder object using:Cylinder cy = new Cylinder();

Memory is allocated for the entire object: radius and length Both initialized to 0.0d No constructor parameter for cylinder No this() call for cylinder super() is called explicitly for Circle No parameter for circle Explicit this(1.0) call for circle Set parameter r = 1.0 for Circle(double r) No explicit this call for Circle(double r) call Super() for Object

Inheritance-27 For use of IST410 students only

Memory Allocation

No parameter setting necessary for Object No this() call for Object No super() call for Object No explicit initialization or constructor body for Object No explicit initialization for radius of Circle Execute body of Circle constructor: set radius = parameter r No explicit initialization for Cylinder instance variable length Execute constructor body for the Cylinder: set length = 1.0

Inheritance-28 For use of IST410 students only

Polymorphism

Polymorphism is the ability of an Object to have many forms

For example, consider the area method of Circle The Cylinder subclass has its own way of calculating the

area: the area operation is polymorphic since it has many forms

In a world of non-polymorphic programming, we would need to distinguish the area operation for each class and create artificial operation such as CircleArea and CylinderArea

This is inflexible since we may need a sphereArea and so on

Inheritance-29 For use of IST410 students only

Polymorphism

An alternative choice is to define an area for the base class and override the method in each of the subclasses

In this scenario, the object decides which area method to use at run-time

How does the JVM resolve which method to apply when we execute a statement of the form obj.method()?

JVM looks for the method in the current class first If not found, JVM looks for the method in the immediate super

class The process continues until Object is reached If not found, an error is reported

Inheritance-30 For use of IST410 students only

Polymorphism

One of the keys to using polymorphism is to declare objects of general superclass type but assign objects of subclasses

Circle c = new Cylinder(); The run-time environment is then made responsible to

determine which method to invoke i.e that of Circle or Cylinder

This enables a programmer to be flexible in designing methods that can handle any object in an inheritance hierarchy

Inheritance-31 For use of IST410 students only

Polymorphism

However, an object has only one form. Thus an assignment of the type

Circle c = new Cylinder();does create practical complications

For the compiler, c is still an object of type Circle Therefore, using c, only members of the Circle class can

be invoked, anything else would be considered illegal This problem can be overcome through type checking and

casting

Inheritance-32 For use of IST410 students only

Polymorphism

Assuming that volume() is a method of the Cylinder class and not of the Circle, the following code would not compile Circle c = new Cylinder(); // Is OK

double v = c.volume(); // will not compile What compiler thinks:

c is an object of type Circle A Circle object does not have a method called volume() Therefore, compilation of c.volume() cannot proceed

Solution: wrap the code within type checkingif ( c instanceof Cylinder) {

Cylinder cy = (Cylinder) c; ....

Inheritance-33 For use of IST410 students only

Polymorphism: which method is called?

Consider the Circle and Cylinder class and assume that Circle has a method to compute Circumferene

Cylinder c = new Cylinder(); double f = c.circumference(); At execution time, JVM checks for the circumference()

method in the Cylinder (subclass) class Since the method is not found, parent class becomes

responsible and the circumference() method of Circle is used

Inheritance-34 For use of IST410 students only

Polymorphism: which method is called?

Consider the Circle and Cylinder class again and assume that both Circle and Cylinder have a method to compute area

Circle c = new Cylinder(); double f = c.area(); Compilation is successful since Circle has an area method At execution time, JVM checks for the true type of c and it

is a Cylinder JVM applies the area() method of the Cylinder class An object’s ability to decide what method to apply to

itself, depending upon its position in the inheritance hierarchy is usually a polymorphic behavior

Inheritance-35 For use of IST410 students only

Polymorphism

Key to polymorphism is late binding Code for the method call is not generated until run time Every time a method is called in the inheritance hierarchy,

dynamic binding is applied at run time Normal binding technique is static

Inheritance-36 For use of IST410 students only

Casting objects

In Java, an object cannot be cast as another object Casting is allowed only when the compiler is satisfied that

such casting is possible Rules:

casting a subclass object to superclass is not necessary; you are promising less

assigning superclass to subclass - explicit cast is needed; you are promising more. Cast will be allowed only if the promise can be kept.

Inheritance-37 For use of IST410 students only

Casting objects

Circle c = new Cylinder(); // Is OK double d = c.area(); // what is executed? // do appropriate processing if ( c instanceof Cylinder) { Cylinder cy = (Cylinder) c; // cast to Cylinder // process for cy } Casting is allowed since c is truely a Cylinder

Inheritance-38 For use of IST410 students only

Abstract class

Abstract class is like any other class can contain methods and data members methods can be abstract and non-abstract data members can be static or non-static

A class is abstract if at least one method is abstract An abstract method dos not have an implementation A class can be declared abstract even if it has no abstract

method An abstract class cannot be instantiated Only descendant non-abstract classes can be instantiated

Inheritance-39 For use of IST410 students only

Abstract class: Example

import java.util.*; //Merchandize.javapublic abstract class Merchandize { private long productCode; private double unitPrice;

private Calendar manfDate; public Merchandize() { } public Merchandize(long p, double u,

Calendar g) { productCode = p; unitPrice = u; manfDate = g; } public long getCode() { return productCode; } public double getPrice() { return unitPrice; }

public String getManfDate() { int yr = manfDate.get(Calendar.YEAR); int mon = manfDate.get(Calendar.MONTH); int day =

manfDate.get(Calendar.DAY_OF_MONTH); String d = mon+"/"+day+"/"+yr; return d; }

public abstract void draw(); public abstract String warning();}

Merchandize is an abstract class and contains two abstract methods: draw, warning

Inheritance-40 For use of IST410 students only

Extending Abstract class: Example

import java.util.*; //Soup.javapublic class Soup extends Merchandize { private String manfName; public Soup() { super();

manfName = null; } public Soup(long code, double pr, Calendar m,

String n) { super(code,pr,m);

manfName = n; } public String getManfName() { return manfName; } public String warning() { return "This soup is quite safe"; } public void draw() {

System.out.println("No picture on file for this product");

}

public static void main(String args[]) { String manf = "Soup King";

long code = 121L;double pr = 23.29;Calendar gc = new GregorianCalendar(TimeZone.getDefault(),

Locale.getDefault());Soup sk = new Soup(code,pr,gc, manf);System.out.println("Product code = ” +

sk.getCode());System.out.println("Unit Price = ” +

sk.getPrice()); System.out.println("Manufacturing date = ” +

sk.getManfDate()); System.out.println("Manufacture's name = ” + sk.getManfName());

System.out.println("Picture of product");sk.draw();System.out.println("product warning message = ” + sk.warning());}

}

Inheritance-41 For use of IST410 students only

Rational for Abstract class

Consider the Merchandize class - it can be used to represent any merchandize in a store

Some products may have mandated warning, many may have pictures for display

How do we draw the picture without knowing which specific merchandize we are dealing with?

Soup, on the other hand, is a concrete class and we would know how to draw its picture

Similarly, we can put warning messages only for those subclasses that must carry such a warning: Cigarettes for example

Inheritance-42 For use of IST410 students only

Rational for Abstract class

In general, as you travel up an inheritance hierarchy, classes become progressively more general. It is difficult to define their behavior.

The subclasses are progressively more concrete and their behavior can be defined

Abstract methods are used in the super class to provide a common structure that all subclasses promise to implement

Subclasses then override the abstract methods to provide the applicable behavior for the class

Important: since a subclass inherits from its parent, the subclass must implement all abstract methods of the superclass, otherwise it becomes abstract

Inheritance-43 For use of IST410 students only

Interfaces

Interface is an abstract class where all methods are abstract It can contain data members, however, they must all be

static and final Can be used to implement multiple inheritance through

which a class can implement common behaviors from more than one parent

A class can implement one or more interfacespublic class X extends Y implements A, B { .... }

where A and B are two interfaces

Inheritance-44 For use of IST410 students only

Interface Example

Consider the ++ operator that adds one to its integral operand

Suppose we want to add this behavior for a few classes We can define an interface with an abstract method

public interface IncrementOperator {public void pp();

} Other classes can now implement this interface and

provide a definition for the abstract method

Inheritance-45 For use of IST410 students only

Use of Interface: MyFloat.java

public class MyFloat implements IncrementOperator {private float num;public MyFloat() {}public MyFloat(float f) { num = f;}public void pp(){ num += 1.0;}public float getValue(){

return num;}public static void main(String args[]){

MyFloat mf = new MyFloat(3.4f);System.out.println("Start value = "+mf.getValue());mf.pp();System.out.println("After increase = "+mf.getValue());

}}

Implementation of the abstract method declared in the interface. Compare this implementation to that in PointWithPP class

Declaring the intention to implement an Interface

Inheritance-46 For use of IST410 students only

Use of Interface: PointWithPP.java

public class PointWithPP implements IncrementOperator { private int x, y; public PointWithPP() { } public PointWithPP(int x, int y) {

this.x = x; this.y = y;

} public void pp(){

x++; y++;

} public void showCoordinates(){

System.out.println("x = "+x+" y = "+y); } public static void main(String args[]){

PointWithPP pt = new PointWithPP(10,15);pt.showCoordinates();pt.pp();pt.showCoordinates();

}}

Implementation of the abstract method declared in the interface. Notice that this implementation is significantly different from that in MyFloat class

Declaring the intention to implement an Interface

Inheritance-47 For use of IST410 students only

Exercise

Define an Interface called MathOperator with methods for the following

add 1 to a number subtract 1 from a number add an integer number supplied as an argument subtract an integer supplied as an argument print - prints the number value

Write a class called MyInt that defines exactly one integer as its instance variable. This class implements the MathOperator; add appropriate constructor

Write another class MyFloat that defines exactly one float as its instance variable. This class also implements the MathOpertaor; add appropriate constructor


Recommended