CS 116 - IIT Computer Science Department

Download Report

Transcript CS 116 - IIT Computer Science Department

CS 116

OBJECT ORIENTED PROGRAMMING II LECTURE 7 GEORGE KOUTSOGIANNAKIS

Copyright: 2014/ Illinois Institute of Technology/George Koutsogiannakis

Last week’ s topics

• Continue with multi dimensional arrays – Multidimensional Arrays – ArrayList 2

This Lecture ’s topics

• • Inheritance Concepts Inheritance Design – Inherited Members of a Class – Subclass Constructors – Overriding Inherited Methods 3

Inheritance Concepts

• • • • A common form of reuse of classes is inheritance We can organize classes into functionality hierarchies of The class at the top of the hierarchy ( superclass ) defines instance variables and methods common to all classes in the hierarchy We derive a subclass , which inherits fields from the superclass behavior and 4

What is the Advantage?

• • If Class B inherits Class A then: – All the methods that class A has are also members of Class B.

– All public instance variables of Class A are also members of Class B.

– That means that Class B can use these public members of Class A without using an objcet of Class A to invoke them. In this example Class A is called the SUPERCLASS and Class B is called the SUBCLASS 5

A Sample Vehicle Hierarchy

This hierarchy is depicted using a Unified Modeling Language (UML) diagram.

In UML diagrams, arrows point from the subclass to the superclass.

6

Superclasses and Subclasses

• • • • A superclass can have multiple subclasses Subclasses can be superclasses of other subclasses A subclass can inherit directly from only one superclass – Multiple inheritance is not allowed in Java (C++ allows multiple inheritance).

All classes inherit from the Object class 7

Superclasses and Subclasses

• In this example: – If our superclass Vehicle has methods calculateV and calculateD then – All the subclasses (Automobile, Truck, Pickup, TractorTrailer) get to use these methods without an object of Vehicle to invoke them.

– i.e I class Pickup to calculate the velocity of a Pickup object we will call: double vel=calculateV(); 8

Multiple Inheritance

• • In the examples thus far we used Single Inheritance: – That means that a subclass can only inherit from a one superclass.

Multiple Inheritance means that a subclass can inherit from more than one superclass.

– Some languages allow that (i.e. C++).

– Java DOES Not allow it.

9

Multiple Inheritance

• The concept of multiple inheritance is shown below (even though Java does not allow it).

Class A Class B Class C Class D 10

Superclasses and Subclasses

• • • A big advantage of inheritance is that we can write code that is common to multiple classes once and reuse it in subclasses A subclass can define new methods and instance variables, some of which may override (hide) those of a superclass

Remember that the subclass gets to use the methods of its superclass as if they were its own (just call them without using an object to invoke them)

11

When Do We have Inheritance?

• • • • We have inheritance if a “is a” relationship exists between classes.

For instance, assume that we have the class Auto.

If we were to create a new class called SUV then we can say that

SUV is an Auto.

Therefore our new class SUV could inherit the class Auto.

12

Specifying Inheritance

The syntax for defining a subclass is to use the extends keyword in the class header, as in: • accessModifier class SubclassName extends SuperclassName { // class definition } The superclass name specified after the extends keyword is called the direct superclass As mentioned, a subclass can have many superclasses, but only one direct superclass 13

Direct Superclass

Class C Class B Class B is the Direct Superclass Class A Class A inherits from Class B but it also inherits indirectly Class C.

14

• • • • A JApplet Hierarchy example (Library classes follow inheritance rules also) A JApplet is a library class that allows the creation of a graphical container, we defined a subclass.

We say that inheritance implements an " is a " relationship, in that a subclass object "is a" super class object as well.

Thus, a class RollABall "is a" JApplet (its direct super class), Applet, Panel, Container, Component, and Object.

RollABall begins with more than 275 methods and 15 fields inherited from its 6 super classes.

15

The BankAccount Heirarchy

Note 1: + indicates public and – indicates private Note 2: return types Are shown after the Name and arguments listing of a method 16

The BankAccount Class

The BankAccount class is the superclass.

– Instance variables: • • balance (double) MONEY (a constant DecimalFormat object) – Methods: • • Default and overloaded constructors deposit and withdraw methods • balance accessor •

toString See Example 10.1 BankAccount.java

17

The CheckingAccount Class

We derive the CheckingAccount subclass from

BankAccount:

public class CheckingAccount extends BankAccount { } A subclass inherits the public members of a superclass (except constructors). Thus, the CheckingAccount class inherits – the MONEY instance variable – The getBalance, deposit, withdraw, and toString methods

See Example 10.2 CheckingAccount.java

and Example 10.3 CheckingAccountClient.java

18

private Members

• • • • Super class members declared as private are not inherited, although they are part of the subclass.

Thus, a balance instance variable is allocated to all CheckingAccount objects, but methods of the CheckingAccount class cannot directly access balance.

To set or get the value of balance, the CheckingAccount methods must call the withdraw, deposit, or getBalance methods.

This simplifies maintenance because the BankAccount class enforces the data validation rules for balance.

19

protected Members

• • • protected members are inherited by subclasses (like public members), while still being hidden from client classes (like private members). Also, any class in the same package as the superclass can directly access a protected field, even if that class is not a subclass. Disadvantage: – Because more than one class can directly access a protected field, protected access compromises encapsulation and complicates maintenance. – For that reason, we prefer to use private, rather than protected, for our instance variables.

20

Superclass Members

public

fields

public

methods

protected

fields

protected

methods

private

fields

Inherited by subclass?

yes

Inheritance Rules

Directly Accessible by Subclass?

Directly Accessible by Client of Subclass?

yes yes yes no yes, by using field name yes, by calling method from subclass methods yes, by using field name yes, by calling method from subclass methods no, must call accessors and mutators yes yes no, must call accessors and mutators no no, must call accessors and mutators

private

methods no no no 21

Subclass Constructors

• • • • Constructors are not inherited.

However, the subclass can call the constructors of the superclass to initialize inherited fields.

Implicit – invocation The default constructor of the subclass automatically calls the default constructor of the superclass.

For explicit invocation, use this syntax: super( argument list ); If used, this statement must be the first statement in the subclass constructor.

22

CheckingAccount Constructors

public CheckingAccount( ) { // optional explicit call // to BankAccount default constructor super( ); } public CheckingAccount( double startBalance ) { // explicit call to BankAccount // overloaded constructor super( startBalance ); }

See Examples 10.4 , 10.5, and 10.6

23

Common Error Trap

An attempt by a subclass to directly access a private field or call a private method defined in a superclass will generate a compiler error. – To set initial values for private variables, call the appropriate constructor of the direct superclass.

For example, this statement in the overloaded CheckingAccount class constructor calls the overloaded constructor of the BankAccount class: super( startBalance ); 24

Example

• • • Consider the class Vehicle that we have been using in our lab assignments.

Suppose that we create the class public class AutoRacing extends Vehicle In this class we can now use the public methods and public fields of class Vehicle without creating an object of Vehicle and then invoking its methods.

25

Example

} • { public class Vehicle { ….. Same members a sin the Labs and exercises } public class AutoRacing extends Vehicle { public void some method() …. Some code.. } 26

Example

• The client of AutoRacing class gets access to both classes with one object public class AutoRacingClient { public static void main (String[] args) { ………………some code……..

AutoRacing ar= new AutoRacing(); double vel= ar.calculateV(); …………..

} } Notice that the object ar can invoke the method calculateV which belongs to Vehicle class. 27

SOFTWARE ENGINEERING TIP

• Overloaded constructors (same as non default constructors) in a subclass should explicitly call the direct super class constructor to initialize the fields in its super classes. 28

Inheritance Rules for Constructors

Superclass Members

constructors

Inherited by subclass?

no

Directly Accessible by Subclass?

yes, using super( arg list ) in a subclass constructor

Directly Accessible by Client of Subclass Using a Subclass Reference?

no 29

The BankAccount Heirarchy

Note 1: + indicates public and – indicates private Note 2: return types Are shown after the Name and arguments listing of a method 30

Adding Specialization

A subclass can define new fields and methods that the superclass does not have. That is calle dspecialization.

Our CheckingAccount class adds – these instance variables: • monthlyFee, a doubleDEFAULT_FEE, a double constant – these methods: • • setMonthlyFee, the accessor getMonthlyFee, the mutator • applyMonthlyFee, which charges the monthly fee to the account 31

abstract Classes and Methods

An abstract class is a class that is not completely implemented.

Usually, the abstract class contains at least one abstract method .

– An abstract method specifies an API but does not provide an implementation.

– The abstract method is used as a pattern for a method the subclasses should implement.

32

More on abstract Classes

An object reference to an abstract class can be declared. – We use this capability in polymorphism, which will be discussed later.

An abstract class cannot be used to instantiate objects (because the class is not complete). An abstract class can be extended.

– subclasses can complete the implementation and objects of those subclasses can be instantiated 33

Example Abstract Class

• Suppose we declare our class Vehicle abstract and add a method besides the other methods that it has called calculateT (i.e. this method calculates the time taken by a Vehicle object to travel a specified distance): public abstract class Vehicle { //existing members public abstract double calculateT(); }

Notice that our method calculateT does not have any code associated with it. It would be the responsibility of the subclasses of Vehicle to implement the code

.

34

Defining an abstract class

To declare a class as abstract, include the abstract keyword in the class header: accessModifier abstract class ClassName { // class body } 35

Defining an abstract Method

To declare a method as abstract, include the abstract keyword in the method header, and end the header with a semicolon: accessModifier abstract returnType methodName( argument list ); Note: – The semicolon at the end of the header indicates that the method has no code.

– We do not use opening and closing curly braces { }.

36

Subclasses of abstract Classes

• • • • • A subclass of an abstract class can implement all, some, or none of the abstract methods. An abstract class Figure could have an abstract method called draw. Notice that draw has no

implementation just a definition (i.e. pblic void draw(); )

If the subclass does not implement all of the abstract methods, it must also be declared as abstract.

For example a Circle subclass that inherits Figure class adds a radius instance variable and implements the draw method.

Another class called Square (subclass) that inherits Figure adds a length instance variable and implements the draw method.

Therefore each of the subclasses implements draw in a different way each.

See Examples 10.15, 10.16, 10.17, & 10.18 in text

37

Study Guide

• Chapter 10 – Sections 10.1, 10.2.1, 10.2.2

38