more on classes inheritance and polymorphism section 7/8

30
More on Classes Inheritance and Polymorphism Section 7/8

Upload: hailey-gonzalez

Post on 28-Mar-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: More on Classes Inheritance and Polymorphism Section 7/8

More on Classes Inheritance and Polymorphism

Section 7/8

Page 2: More on Classes Inheritance and Polymorphism Section 7/8

Learning objectives

• Explore the role of inheritance in object-oriented design.

• Introduce polymorphism.• Develop a series of classes demonstrating the power of

the inheritance.• Explore superclasses and subclasses in Java.• Introduce abstract classes.

Page 3: More on Classes Inheritance and Polymorphism Section 7/8

Inheritance

• Organizes objects in a top-down fashion from most general to least general

• Inheritance defines an “is-a” relationship• A mountain bike “is a” kind of bicycle• A SUV “is a” kind of automobile• A border collie “is a” kind of dog• A laptop “is a” kind of computer

• The is-a relationship is used to help us understand or even establish a class relationship

Page 4: More on Classes Inheritance and Polymorphism Section 7/8

Musical instrument hierarchy

Aerophones

MusicalInstruments

Reeded

Clarinets Saxophones Bassoons

Page 5: More on Classes Inheritance and Polymorphism Section 7/8

Musical instrument hierarchy

• The hierarchy helps us understand the relationships and similarities of musical instruments

• A clarinet “is a” kind of reeded instrument

• The “is-a” relationship is transitive• A clarinet “is a” kind of lip reeded instrument• A reeded instrument “is a” kind of aerophone• A clarinet “is a” kind of aerophone

Girl

Life-form

Mammal

Human

Is-a

Is-a

Is-a

Page 6: More on Classes Inheritance and Polymorphism Section 7/8

Object-oriented terminology

• In object-oriented programming languages, a class created by extending another class is called a subclass.

• The class used for the basis is called the superclass

• Alternative terminology• The superclass is also referred to as the base class• The subclass is also referred to as the derived class

Subclass

Superclass

Is-a

Page 7: More on Classes Inheritance and Polymorphism Section 7/8

Return to Inheritance

• Inheritance is means of organizing related classes• The term inheritance refers to the fact that one class can inherit

part or all of its structure and behaviour from another class.

• The class that does the inheriting is said to be a subclass of the class from which it inherits. If class B is a subclass of class A, we also say that class A is a superclass of class B.

• A subclass can add to the structure and behaviour that it inherits. It can also replace or modify inherited behaviour (though not inherited structure).

Page 8: More on Classes Inheritance and Polymorphism Section 7/8

What Is Inheritance?

In Java, when you create a new class, you can declare that it is a subclass of an existing class. If you are defining a class named "B" and you want it to be a subclass of a class named "A", you would write

class B extends A {.

. // could include many additions to, and modifications of,// the code inherited from

class A

}

Page 9: More on Classes Inheritance and Polymorphism Section 7/8

Superclass and Subclass

• Several classes can be declared as subclasses of the same superclass. The subclasses (sibling classes) share some structures and behaviour they inherit from their common superclass.

• Structure is give by the type of the class, ex. if the superclass is a “life-form” then the subclasses are all going to have the same type, that is a life-form.

Behaviour is determined by the actions of the life-form. You would expect this to be very different from a subclass inheriting behavior from the class musical instrument.

Page 10: More on Classes Inheritance and Polymorphism Section 7/8

Superclass and Subclass

• In the diagram, classes B, C, and D are sibling classes. Inheritance can also extend over several "generations" of classes.

• This is shown in the diagram, where class E is a subclass of class D which is itself a subclass of class A. In this case, class E is a subclass of class A, even though it is not a direct subclass.

Page 11: More on Classes Inheritance and Polymorphism Section 7/8

An example of inheritance

• Suppose that a program has to deal with motor vehicles, including cars, trucks, and motorcycles, etc. (This might be a program used by the DVLA to keep track of registrations.)

• The program could use a superclass named Vehicle to represent all types of vehicles.

• The Vehicle class could include:

instance variables such as registrationNumber, owner and address instance methods such as transferOwnership() and changeAddress()

Page 12: More on Classes Inheritance and Polymorphism Section 7/8

An example of inheritance

• Three subclasses of Vehicle:

• Car, Truck, and Motorcycle -- could then be used to hold variables and methods specific to particular types of vehicles.

• The subclass Car might add instance variable and methods:• The Car class might add

– instance variable numberOfDoors, • the Truck class might add

– instance variable numberOfAxels, • the Motorcycle class could add

– boolean instance variable hasSidecar.

Page 13: More on Classes Inheritance and Polymorphism Section 7/8

Class Vehicle

• The declarations of these classes in Java program would look, in outline, like this: class Vehicle { int registrationNumber; String owner; // instance variable owner void transferOwnership(String newOwner) { // instance method . . . } } class Car extends Vehicle { int numberOfDoors; // Instance variable . . . } class Truck extends Vehicle { int numberOfAxels; . . . } class Motorcycle extends Vehicle { boolean hasSidecar; . . . }

// Note the use of extends in declaring each of the subclass

Page 14: More on Classes Inheritance and Polymorphism Section 7/8

Class Vehicle

Note, Car is-a vehicleTruck is-a vehicleMotorcycle is-a vehicle ALL OK

However, Vehicle is-a Car not trueetc

USE IS-A TEST TO ENSURE YOU HAVE THE CORRECT RELATIONSHIP.

Page 15: More on Classes Inheritance and Polymorphism Section 7/8

Class Vehicle• Suppose that myCar is a variable of type Car that has been declared and

initialised with the statementCar myCar = new Car(); myCar is an object of class Car

As class Car extends class Vehicle, a Car also has all the structure and behaviour of a Vehicle.

Page 16: More on Classes Inheritance and Polymorphism Section 7/8

Class Vehicle

• Now myCar is-a Car and also is-a Vehicle, therefore the methods and instance variable of Vehicle are also available to Car.

• this means that myCar.registrationNumber,

myCar.owner

myCar.transferOwnership()

also exist.

• The practical effect of this is that an object of type Car can be assigned to a variable of type Vehicle.

Page 17: More on Classes Inheritance and Polymorphism Section 7/8

Class Vehicle

• Thus, it would be legal to say

Vehicle myVehicle = myCar;

• or even

Vehicle myVehicle = new Car();

• The object "remembers" that it is in fact a Car, and not just a Vehicle.

Page 18: More on Classes Inheritance and Polymorphism Section 7/8

Class Vehicle• Information about the actual class of an object is stored as part of that

object. It is even possible to test whether a given object belongs to a given class, using the instanceof operator.

• The test:

if (myVehicle instanceof Car) ...

determines whether the object referred to by myVehicle is in fact a Car.

• On the other hand, if myVehicle is a variable of type Vehicle the assignment statement

myCar = myVehicle;

would be illegal because myVehicle could potentially refer to other types of Vehicle that are not Car.

Page 19: More on Classes Inheritance and Polymorphism Section 7/8

Class Vehicle

Thus, you are not allow to assign a value of type Vehicle to an object of type Car because not every vehicle is a Car.

• The solution here is to use type-casting. So, you could say:

myCar = (Car)myVehicle;

and you could even refer to ((Car)myVehicle).numberOfDoors.

Page 20: More on Classes Inheritance and Polymorphism Section 7/8

Use of super

When we extend superclass to a new subclass we can make use of the constructors of the superclass by using the keyword super:

super( ); invocation of superclass default constructor

super(a, b); invocation of specific superclass constructor

Examples to come later

Page 21: More on Classes Inheritance and Polymorphism Section 7/8

Overriding a method

• Overriding• When a class is inherited the new class may need to provide a new

version of a given method in the base class. • When a sub-class method is identical in name and the number and type

of arguments as a method in the class it is inheriting, it is said to override that method.

public class A {  int i=0;  void doSomething() {i=5;}}class B extends A {  int j=0;  void doSomething(){    j=10;     i=15;  }}

doSomthing in class B overrides doSomthing in class A

Page 22: More on Classes Inheritance and Polymorphism Section 7/8

Polymorphism

• A code expression can invoke different methods depending on the types of objects being manipulated

• Example: function overloading like method min() from java.lang.Math

• The method invoked depends on the types of the actual arguments

• Exampleint a, b, c;double x, y, z;…c = min(a, b); // invokes integer min()z = min(x, y); // invokes double min()

Page 23: More on Classes Inheritance and Polymorphism Section 7/8

Polymorphism

• Two types of polymorphism• Syntactic polymorphism—Java can determine which method to

invoke at compile time• Efficient• Easy to understand and analyze

• Pure polymorphism—the method to invoke can only be determined at execution time

Page 24: More on Classes Inheritance and Polymorphism Section 7/8

Abstract and Concrete Classes

• An abstract class defines data and methods common to all subclasses, but is never instantiated

• A concrete class inherits some data and methods, defines others, and is instantiated

Page 25: More on Classes Inheritance and Polymorphism Section 7/8

Abstract class

• An abstract class contains empty declaration as well as concrete definitions of methods and/or instance variables.

• An abstract class cannot be instantiated:

• The extension rules apply to an abstract class:

- that is, no object can be created from an abstract class

- thus an abstract class can extend another abstract class, but further, a concrete class can extend an abstract class.

Page 26: More on Classes Inheritance and Polymorphism Section 7/8

Why abstract class?

• When an existing class is extended you may wish to force the programmer to redefine a method.

• example:

public class BankAccount{

public void bankCharge( ){ .............}

}• The method bankCharge could have a specific charge which is not

appropriate in a subclass

- better to declare an abstract method:public abstract void bankCharge( );

Page 27: More on Classes Inheritance and Polymorphism Section 7/8

Abstract method

• An abstract method has no implementation• - forces the implementers of subclasses to specify concrete

implementations:

public abstract class BankAccont{

public abstract void bankCharge( );........... other methods

}

• Note, abstract classes can have instance variables and some concrete methods, however they cannot be instantiated.

Page 28: More on Classes Inheritance and Polymorphism Section 7/8

Inheriting abstract classes

• When you derive a class from an abstract class, you do not have to define all the abstract methods in the subclass.

• - then the subclass is also an abstract class. Therefore you cannot instantiated this class as objects.

• At some level you will have a class that contains no abstract methods. This will be a concrete class which can be used to define objects.

AC

AC AC

CC CC CC CC

BankAccount

ChequeAccount SavingsAccount

PersonalAcct BusinessAcct HighInterestAcctChildAcct

Page 29: More on Classes Inheritance and Polymorphism Section 7/8

Example: Data Model ClassesShape

Rectangle TriangleCircle

The Shape class is abstract, whereas the otherclasses are concrete.

All shapes have a position, a size, and a color.Specific shapes have different ways to be drawn.

Page 30: More on Classes Inheritance and Polymorphism Section 7/8

Dynamic binding

• Suppose a class A has one or more subclasses. Then program code that apparently refers to objects of type A can be used to process objects belong to A’s subclasses.

• Java will wait until the code is executing before deciding which types of objects are being processed, and will then call the appropriate methods. This feature is called dynamic binding.

• For example, in the Book index example, both class Book and class Periodical extent class Item. Thus, when the statement it.display() is executed, Java will check the object referred to by it and will call the appropriate display method, depending on whether it refers to a Book or a Periodical.