inheritance, abstract classes, interface and polymorphism

70
Inheritance, Abstract Classes, Interface and Polymorphism

Upload: dianne

Post on 26-Feb-2016

75 views

Category:

Documents


6 download

DESCRIPTION

Inheritance, Abstract Classes, Interface and Polymorphism. Objectives. Understand class hierarchies and polymorphism Learn about abstract classes Learn the syntax for calling superclass’s constructors and methods. Understand interfaces Deriving new classes from existing classes - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Inheritance, Abstract Classes, Interface and Polymorphism

Inheritance, Abstract Classes, Interface and Polymorphism

Page 2: Inheritance, Abstract Classes, Interface and Polymorphism

Objectives

• Understand class hierarchies and polymorphism

• Learn about abstract classes

• Learn the syntax for calling superclass’s constructors and methods

• Understand interfaces

• Deriving new classes from existing classes

• The protected modifier

• Indirect visibility of inherited members

• Designing for inheritance

Page 3: Inheritance, Abstract Classes, Interface and Polymorphism

Inheritance• Classes are the blueprints and objects are the

houses.• Inheritance – lets say you want to keep the same

basic features of a blueprint but want to change it a little and create a new blueprint by using the old and adding to it. This can thought of as inheritance.

• Inheritance takes one class and adds to another class by using the keyword extends.

• Inheritance – is how a new class is created from an existing class.

• The main purpose of inheritance is to reuse existing software making it easier, cheaper and using already tested code.

Page 4: Inheritance, Abstract Classes, Interface and Polymorphism

Inheritance

• Inherited variables and methods can be used in the derived class as if they had been declared locally.

• Inheritance creates an “is-a” relationship between all parent and child classes.

Page 5: Inheritance, Abstract Classes, Interface and Polymorphism

Inheritance• The existing class is called the parent class, or

superclass, or base class

• The derived class is called the child class or subclass

• As the name implies, the child inherits characteristics of the parent

• That is, the child class inherits the methods and data defined by the parent class

Page 6: Inheritance, Abstract Classes, Interface and Polymorphism

“is – a” relationship example• Lets say you have a class called Mammal.

Mammal will be the parent or super class. The Mammal classes will contain all general methods and variables that all mammals has.

• Now let say you have a Class Horse. A Horse “is – a” Mammal. So since Horse is a Mammal, not only will Horse contain all the features of Mammal, since a Horse is a mammal, but it will also contain more specific methods and variable that only a horse has that other mammals may or may not have.

• Horse will be the subclass or child class.

Page 7: Inheritance, Abstract Classes, Interface and Polymorphism

Keyword “extend”

• We use the keyword extend in the child class to inherit the parent’s class methods and variables.

Page 8: Inheritance, Abstract Classes, Interface and Polymorphism

Examplepublic class Book{ public int pages = 1500; public void pageMessage(){ System.out.println(“Number of pages” + pages); } }

public class Dictionary extends Book{ private int definitions = 525000; public void definitionMessage(){ System.out.println(“Number of def “ + definitions); System.out.println(Definition per page” + definition/pages);}

public class Word{public static void main(Strings[] args){ Dictionary webster = new Dictionary(); webster.pageMessage(); webster.definitionMessage(); } }

Output:Number of pages: 1500Number of def 52500Definition per page 35

Page 9: Inheritance, Abstract Classes, Interface and Polymorphism

Graphical representation of inheritance

Arrow always points from the child to the parent

Mammal Book

Horse Dictionary

Page 10: Inheritance, Abstract Classes, Interface and Polymorphism

Inheritance Facts

• Not all variables and methods are inherited.• The only variables and methods that are inherited

are those that are declared as public in the parent class.

• The child class does not inherit the methods or variables declared as private.

• Constructors are not inherited in by the child class even though it is declared public.

Page 11: Inheritance, Abstract Classes, Interface and Polymorphism

Rules of inheritance

• By the constructor not being inherited, breaks the rule of inheritance. This is an exception to the rule that all public methods and variables are inherited. Remember that constructors are declare as public.

• Encapsulation – By declaring variables public breaks the rule of encapsulation and therefore all variables should be declared private and use methods to change and access variables.

Page 12: Inheritance, Abstract Classes, Interface and Polymorphism

Inheritance

• Inheritance represents the IS-A relationship between objects: an object of a subclass IS-A(n) object of the superclass.

Superclass(Base class)

Subclass(Derived class)

Subclass extends Superclass

Page 13: Inheritance, Abstract Classes, Interface and Polymorphism

Single inheritance

• Java only allows single inheritance.• This term means that a child class can have

only one parent. • ** Other languages allow multiple

inheritance. Can be difficult.

Page 14: Inheritance, Abstract Classes, Interface and Polymorphism

Multiple Inheritance• Java supports single inheritance, meaning that a

derived class can have only one parent class

• Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents

• Collisions, such as the same variable name in two parents, have to be resolved

• Java does not support multiple inheritance

• In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead

Page 15: Inheritance, Abstract Classes, Interface and Polymorphism

Super

• Super can be used in a class to refer to its parent class.

• A parent’s constructor can be invoked using the super reference.

• Super also allows us to reference members of the parent class.

Page 16: Inheritance, Abstract Classes, Interface and Polymorphism

Super()

• The first line of a constructor uses the super reference of the parent class.– This way the parent class always initializes its

variables before the child class constructor begins to execute.

Page 17: Inheritance, Abstract Classes, Interface and Polymorphism

Overriding Methods

• What happens if a child and parent class share the same method name and signature?

• The child method will override the parent’s method that is inherited.

Page 18: Inheritance, Abstract Classes, Interface and Polymorphism

Class Hierarchies

• A child class can be a parent of its own child class.

• Common features should be kept as high in the hierarchy as possible.

• Example: Animal

Bird

Parrot

Page 19: Inheritance, Abstract Classes, Interface and Polymorphism

Class Hierarchy

• Always use an is-a relationship• The inheritance goes all the way down a

hierarchy• That is, a parent passes along a trait to a

child, and the child class passes it long to its children, and so on.

Page 20: Inheritance, Abstract Classes, Interface and Polymorphism

Class Hierarchies • Using inheritance, a programmer can define

a hierarchy of classes.

Biped

Walker Hopper Dancer

ToedInWalker CharlieChaplin

Page 21: Inheritance, Abstract Classes, Interface and Polymorphism

Class Hierarchies (cont’d)• Help reduce

duplication of code by factoring out common code from similar classes into a common superclass.

Biped Constructor Accessors turnLeft turnRight turnAround draw

Walker Constructor firstStep nextStep stop distanceTraveled

Hopper Constructor firstStep nextStep stop distanceTraveled

Page 22: Inheritance, Abstract Classes, Interface and Polymorphism

Class Hierarchies (cont’d)• Help reduce duplication of code by letting

you write more general methods in client classes.

public void moveAcross (Walker creature, int distance) { creature.firstStep(); while (creature.distanceTraveled() < distance) creature.nextStep(); creature.stop(); }

public void moveAcross (Hopper creature, int distance) { creature.firstStep(); while (creature.distanceTraveled() < distance) creature.nextStep(); creature.stop(); }

public void moveAcross (Biped creature, int distance) { creature.firstStep(); while (creature.distanceTraveled() < distance) creature.nextStep(); creature.stop(); }

Works for either Walker or Hopperdue to polymorphism

Page 23: Inheritance, Abstract Classes, Interface and Polymorphism

Class Hierarchies

• A child class of one parent can be the parent of another child, forming a class hierarchy Business

KMart Macys

ServiceBusiness

Kinkos

RetailBusiness

Page 24: Inheritance, Abstract Classes, Interface and Polymorphism

Class Hierarchies• Two children of the same parent are called siblings

• Common features should be put as high in the hierarchy as is reasonable

• An inherited member is passed continually down the line

• Therefore, a child class inherits from all its ancestor classes

• There is no single class hierarchy that is appropriate for all situations

Page 25: Inheritance, Abstract Classes, Interface and Polymorphism

Polymorphism• Is an OOP property in which objects have

the ability to assume different types.• Based on inheritance

– Since a subclass is derived from the superclass, a superclass object can reference an object of the subclass.

• Example:• Circle wafer;• Disk cookie = new Disk(2,0.5)• wafer = cookie; //wafer references cookie

Circle

Disk

Page 26: Inheritance, Abstract Classes, Interface and Polymorphism

Polymorphism

• In the last example, the wafer object, declared a Circle, is polymorphic, as demonstrated in the statement wafer = cookie where wafer assumes the form of cookie, a Disk object.

Page 27: Inheritance, Abstract Classes, Interface and Polymorphism

Polymorphism• What happens when the referenced object

runs an overridden method? Which method runs??

• If Disk overrides toString() & equals() from the parent class Circle, the Disk toString() method would run even though wafer is a Circle object.

• Example:– System.out.println(wafer); // Disk toString()

runs

Page 28: Inheritance, Abstract Classes, Interface and Polymorphism

Polymorphism• Ensures that the correct method is called for

an object of a specific type, even when that object is disguised as a reference to a more generic type, that is, the type of the object’s superclass or some ancestor higher up the inheritance line.

• Once you define a common superclass, polymorphism is just there no need to do anything special.

Page 29: Inheritance, Abstract Classes, Interface and Polymorphism

Polymorphism (cont’d)

public void moveAcross (Biped creature, int distance) { creature.firstStep(); while (creature.distanceTraveled () < distance) creature.nextStep(); creature.stop(); }

The actual parameter passed to this method can be a Walker, a Hopper, etc. any subclass of Biped.

Correct methods will be called automatically for any specific type of creature: Walker’s methods for Walker, Hopper’s for Hopper, etc.

Page 30: Inheritance, Abstract Classes, Interface and Polymorphism

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.Any java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.It is important to know that the only possible way to access an object is through a reference variable. 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 declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

Page 31: Inheritance, Abstract Classes, Interface and Polymorphism

Example:public interface Vegetarian{} public class Animal{} public class Deer extends Animal implements Vegetarian{} Now the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example:• A Deer IS-A Animal• A Deer IS-A Vegetarian• A Deer IS-A Deer • A Deer IS-A ObjectWhen we apply the reference variable facts to a Deer object reference, the following declarations are legal:Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d; All the reference variables d,a,v,o refer to the same Deer object in the heap.

Page 32: Inheritance, Abstract Classes, Interface and Polymorphism

Abstract Classes• Some of the methods in a class can be

declared abstract and left with only signatures defined

• A class with one or more abstract methods must be declared abstract

public abstract class Biped{ ... public abstract void firstStep(); public abstract void nextStep(); public abstract void stop(); ... public void draw(Graphics g) { ... }}

Abstract methods

Page 33: Inheritance, Abstract Classes, Interface and Polymorphism

Abstract Classes (cont’d)• Abstract classes serve as common

superclasses for more specific classes• An abstract method provides an opportunity

for the compiler to do additional error checking

• Abstract classes and methods are needed for polymorphism to work

• Abstract classes are closer to the root of the hierarchy; they describe more abstract objects

Page 34: Inheritance, Abstract Classes, Interface and Polymorphism

Abstract Classes (cont’d)• Java does not allow us to instantiate (that is,

create objects of) abstract classes• Still, an abstract class can have constructors

they can be called from constructors of subclasses

• A class with no abstract methods is called concrete

Page 35: Inheritance, Abstract Classes, Interface and Polymorphism

Calling Superclass’s Constructors

public class Walker extends Biped{ // Constructor public Walker(int x, int y, Image leftPic, Image rightPic) { super(x, y, leftPic, rightPic); ... }}

Biped

Walker

Calls Biped’s constructor

If present, must be the first statement

The number / types of parameters passed to super must match parameters of one of the superclass’s constructors.

Page 36: Inheritance, Abstract Classes, Interface and Polymorphism

Calling Superclass’s Constructors (cont’d)

• One of the superclass’s constructors is always called, but you don’t have to have an explicit super statement.

• If there is no explicit call to super, then superclass’s no-args constructor is called by default.

Must be defined then. If not defined syntax error: cannot find symbol : constructor ...

Page 37: Inheritance, Abstract Classes, Interface and Polymorphism

Calling Superclass’s Constructors (cont’d)

• Superclass’s constructor calls its superclass’s constructor, and so on, all the way up to Object’s constructor.

Biped

Walker

Objectsuper( )

super(...)

Page 38: Inheritance, Abstract Classes, Interface and Polymorphism

Calling Superclass’s Methods

public class CharlieChaplin extends Walker{ ... public void nextStep () { turnFeetIn(); super.nextStep(); turnFeetOut(); } ...}

Walker

CharlieChaplin

Calls Walker’s nextStep

super.someMethod refers to someMethod in the nearest class, up the inheritance line, where someMethod is defined.

Page 39: Inheritance, Abstract Classes, Interface and Polymorphism

Interfaces

DanceFloor

DanceGroup

ControlPanel

Band

Dancer

Aerobics

Waltz

Rumba

Cha-Cha-Cha

Salsa

Dance

Interface

Page 40: Inheritance, Abstract Classes, Interface and Polymorphism

Interfaces (cont’d)• An interface in Java is like an abstract class,

but it does not have any fields or constructors, and all its methods are abstract.

• “public abstract” is not written because all the methods are public abstract.

public interface Dance{ DanceStep getStep (int i); int getTempo (); int getBeat (int i);}

Page 41: Inheritance, Abstract Classes, Interface and Polymorphism

Interfaces (cont’d)• We must “officially” state that a class

implements an interface.• A concrete class that implements an

interface must supply all the methods of that interface.public class Waltz implements Dance

{ ... // Methods: public DanceStep getStep (int i) { ... } public int getTempo () { return 750; } public int getBeat (int i) { ... } ...}

Page 42: Inheritance, Abstract Classes, Interface and Polymorphism

Interfaces (cont’d)• A class can implement several interfaces.• Like an abstract class, an interface supplies

a secondary data type to objects of a class that implements that interface.

• You can declare variables and parameters of an interface type.

• Polymorphism fully applies to objects disguised as interface types.

Dance d = new Waltz( );

Page 43: Inheritance, Abstract Classes, Interface and Polymorphism

Interfaces (cont’d)public interface Edible{ String getFoodGroup(); int getCaloriesPerServing();}

public class Breakfast{ private int myTotalCalories = 0; ... public void eat (Edible obj, int servings) { myTotalCalories += obj.getCaloriesPerServing () * servings; } ...}

Polymorphism: the correct method is called for any specific type of Edible, e.g., a Pancake

public class Pancake implements Edible{ ...}

Page 44: Inheritance, Abstract Classes, Interface and Polymorphism

Classes Interfaces

• A superclass provides a secondary data type to objects of its subclasses.

• An abstract class cannot be instantiated.

• An interface provides a secondary data type to objects of classes that implement that interface.

• An interface cannot be instantiated.

Similarities

Page 45: Inheritance, Abstract Classes, Interface and Polymorphism

Classes Interfaces

• A concrete subclass of an abstract class must define all the inherited abstract methods.

• A class can extend another class. A subclass can add methods and override some of its superclass’s methods.

• A concrete class that implements an interface must define all the methods specified by the interface.

• An interface can extend another interface (called its superinterface) by adding declarations of abstract methods.

Similarities

Page 46: Inheritance, Abstract Classes, Interface and Polymorphism

Classes Interfaces

• A class can extend only one class.

• A class can have fields.

• A class defines its own constructors (or gets a default constructor).

• A class can implement any number of interfaces.

• An interface cannot have fields (except, possibly, some public static final constants).

• An interface has no constructors.

Differences

Page 47: Inheritance, Abstract Classes, Interface and Polymorphism

Classes Interfaces

• A concrete class has all its methods defined. An abstract class usually has one or more abstract methods.

• Every class is a part of a hierarchy of classes with Object at the top.

• All methods declared in an interface are abstract.

• An interface may belong to a small hierarchy of interfaces, but this is not as common.

Differences

Page 48: Inheritance, Abstract Classes, Interface and Polymorphism

DanceStudio

DanceStudio

DanceFloor

DanceGroup

ControlPanel

«interface» Dance Dancer Biped

Foot

CoordinateSystem

DanceStep

A B extends

depends on

has

implements

Band

DanceLesson

«interface» StudentGroup

< various dances >

AbstractDance

Page 49: Inheritance, Abstract Classes, Interface and Polymorphism

The protected Modifier• Visibility modifiers affect the way that class

members can be used in a child class

• Variables and methods declared with private visibility cannot be referenced by name in a child class

• They can be referenced in the child class if they are declared with public visibility -- but public variables violate the principle of encapsulation

• There is a third visibility modifier that helps in inheritance situations: protected

Page 50: Inheritance, Abstract Classes, Interface and Polymorphism

The protected Modifier• The protected modifier allows a child class to

reference a variable or method directly in the child class

• It provides more encapsulation than public visibility, but is not as tightly encapsulated as private visibility

• A protected variable is visible to any class in the same package as the parent class

• Protected variables and methods can be shown with a # symbol preceding them in UML diagrams

Page 51: Inheritance, Abstract Classes, Interface and Polymorphism

Class Diagram for WordsBook

# pages : int

+ pageMessage() : void

Dictionary- definitions : int

+ definitionMessage() : void

Words+ main (args : String[]) : void

Page 52: Inheritance, Abstract Classes, Interface and Polymorphism

The super Reference• Constructors are not inherited, even though

they have public visibility

• Yet we often want to use the parent's constructor to set up the "parent's part" of the object

• The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor

Page 53: Inheritance, Abstract Classes, Interface and Polymorphism

The super Reference

• A child’s constructor is responsible for calling the parent’s constructor

• The first line of a child’s constructor should use the super reference to call the parent’s constructor

• The super reference can also be used to reference other variables and methods defined in the parent’s class

Page 54: Inheritance, Abstract Classes, Interface and Polymorphism

Overriding Methods

• A child class can override the definition of an inherited method in favor of its own

• The new method must have the same signature as the parent's method, but can have a different body

• The type of the object executing the method determines which version of the method is invoked

Page 55: Inheritance, Abstract Classes, Interface and Polymorphism

Overriding

• A method in the parent class can be invoked explicitly using the super reference

• If a method is declared with the final modifier, it cannot be overridden

• The concept of overriding can be applied to data and is called shadowing variables

• Shadowing variables should be avoided because it tends to cause unnecessarily confusing code

Page 56: Inheritance, Abstract Classes, Interface and Polymorphism

Overloading vs. Overriding• Overloading deals with multiple methods with the

same name in the same class, but with different signatures

• Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature

• Overloading lets you define a similar operation in different ways for different parameters

• Overriding lets you define a similar operation in different ways for different object types

Page 57: Inheritance, Abstract Classes, Interface and Polymorphism

Class Object• In Java every class by default extends a

library class Object (from java.lang)• Object is a concrete class

public class Object{ public String toString {...} public boolean equals (Object other) {... } public int hashCode() { ... }

// a few other methods ...}

Methods redefined (overridden) as necessary

Page 58: Inheritance, Abstract Classes, Interface and Polymorphism

The Object Class• A class called Object is defined in the java.lang package of the Java standard class library

• All classes are derived from the Object class

• If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class

• Therefore, the Object class is the ultimate root of all class hierarchies

Page 59: Inheritance, Abstract Classes, Interface and Polymorphism

The Object Class• The Object class contains a few useful methods,

which are inherited by all classes

• For example, the toString method is defined in the Object class

• Every time we define the toString method, we are actually overriding an inherited definition

• The toString method in the Object class is defined to return a string that contains the name of the object’s class along with some other information

Page 60: Inheritance, Abstract Classes, Interface and Polymorphism

The Object Class

• The equals method of the Object class returns true if two references are aliases

• We can override equals in any class to define equality in some more appropriate way

• As we've seen, the String class defines the equals method to return true if two String objects contain the same characters

• The designers of the String class have overridden the equals method inherited from Object in favor of a more useful version

Page 61: Inheritance, Abstract Classes, Interface and Polymorphism

Abstract Classes

• An abstract class is a placeholder in a class hierarchy that represents a generic concept

• An abstract class cannot be instantiated

• We use the modifier abstract on the class header to declare a class as abstract:

public abstract class Product{ // contents}

Page 62: Inheritance, Abstract Classes, Interface and Polymorphism

Abstract Classes• An abstract class often contains abstract methods

with no definitions (like an interface)

• Unlike an interface, the abstract modifier must be applied to each abstract method

• Also, an abstract class typically contains non-abstract methods with full definitions

• A class declared as abstract does not have to contain abstract methods -- simply declaring it as abstract makes it so

Page 63: Inheritance, Abstract Classes, Interface and Polymorphism

Abstract Classes

• The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract

• An abstract method cannot be defined as final or static

• The use of abstract classes is an important element of software design – it allows us to establish common elements in a hierarchy that are too generic to instantiate

Page 64: Inheritance, Abstract Classes, Interface and Polymorphism

Interface Hierarchies• Inheritance can be applied to interfaces as well as

classes

• That is, one interface can be derived from another interface

• The child interface inherits all abstract methods of the parent

• A class implementing the child interface must define all methods from both the ancestor and child interfaces

• Note that class hierarchies and interface hierarchies are distinct (they do not overlap)

Page 65: Inheritance, Abstract Classes, Interface and Polymorphism

Visibility Revisited

• It's important to understand one subtle issue related to inheritance and visibility

• All variables and methods of a parent class, even private members, are inherited by its children

• As we've mentioned, private members cannot be referenced by name in the child class

• However, private members inherited by child classes exist and can be referenced indirectly

Page 66: Inheritance, Abstract Classes, Interface and Polymorphism

Visibility Revisited

• Because the parent can refer to the private member, the child can reference it indirectly using its parent's methods

• The super reference can be used to refer to the parent class, even if no object of the parent exists

Page 67: Inheritance, Abstract Classes, Interface and Polymorphism

Designing for Inheritance• As we've discussed, taking the time to create a

good software design reaps long-term benefits

• Inheritance issues are an important part of an object-oriented design

• Properly designed inheritance relationships can contribute greatly to the elegance, maintainabilty, and reuse of the software

• Let's summarize some of the issues regarding inheritance that relate to a good software design

Page 68: Inheritance, Abstract Classes, Interface and Polymorphism

Inheritance Design Issues• Every derivation should be an is-a relationship

• Think about the potential future of a class hierarchy, and design classes to be reusable and flexible

• Find common characteristics of classes and push them as high in the class hierarchy as appropriate

• Override methods as appropriate to tailor or change the functionality of a child

• Add new variables to children, but don't redefine (shadow) inherited variables

Page 69: Inheritance, Abstract Classes, Interface and Polymorphism

Inheritance Design Issues• Allow each class to manage its own data; use the super reference to invoke the parent's constructor to set up its data

• Even if there are no current uses for them, override general methods such as toString and equals with appropriate definitions

• Use abstract classes to represent general concepts that lower classes have in common

• Use visibility modifiers carefully to provide needed access without violating encapsulation

Page 70: Inheritance, Abstract Classes, Interface and Polymorphism

Restricting Inheritance• The final modifier can be used to curtail inheritance

• If the final modifier is applied to a method, then that method cannot be overridden in any descendent classes

• If the final modifier is applied to an entire class, then that class cannot be used to derive any children at all

– Thus, an abstract class cannot be declared as final

• These are key design decisions, establishing that a method or class should be used as is