ACM/JETT Workshop - August 4-5, 2005 1 02:Inheritance and Interfaces.

43
1 ACM/JETT Workshop - August 4-5, 2005 02:Inheritance and Interfaces

Transcript of ACM/JETT Workshop - August 4-5, 2005 1 02:Inheritance and Interfaces.

1 ACM/JETT Workshop - August 4-5, 2005

02:Inheritance and Interfaces

2 ACM/JETT Workshop - August 4-5, 2005

Inheritance and Interfaces

This is a relatively long lecture and we will cover a number of very important Object-Oriented concepts.

Please note that all the features covered are used in the MarineBiologyCaseStudy.

3 ACM/JETT Workshop - August 4-5, 2005

Topics • Inheritance• Defining a class using inheritance in

Java• Overriding methods• Abstract classes• Substitutability.• Interfaces• Dynamic binding. • Casting

4 ACM/JETT Workshop - August 4-5, 2005

Inheritance

• What is inheritance?

• A class (child class)

–inherits the functionality of another class (parent class), and then

–adds new functionality of its own.

• Java supports single inheritance.

• Inheritance is a requirement of all object-oriented systems.

5 ACM/JETT Workshop - August 4-5, 2005

Inheritance – An Example

CheckingAccounts and SavingsAccounts are types of BankAccounts.

They all have properties like acctId, balance, deposit and withdraw.

But CheckingAccount and SavingsAccount also have some special properties of their own.

6 ACM/JETT Workshop - August 4-5, 2005

Why inheritance• Inheritance is a technique for reuse.

• If a new class has a lot in common with a class that already exists, you can reuse parts of the existing class in the new class.

• The child class is defined by extending the parent class.

• The new ``child'' class has all characteristics of its ``parent'' plus any it adds itself.

7 ACM/JETT Workshop - August 4-5, 2005

Inheritance (an is-a relationship)

• Inheritance is a parent-child relationship between classes.

• The parent class is also called a base class or a superclass.

• The child class is also called a derived class or subclass.

8 ACM/JETT Workshop - August 4-5, 2005

Inheritance – Some Examples

BankAccount is the base class (parent class,superclass)

CheckingAccount and SavingsAccount are the derived classes (child classes,subclasses)

SavingsAccount is-a BankAccount.

CheckingAccount is-a BankAccount

9 ACM/JETT Workshop - August 4-5, 2005

Inheritance

• A child class inheriting from a parent class may

–Define new instance data members and/or methods, and also may

–Override methods inherited from parent class.

10 ACM/JETT Workshop - August 4-5, 2005

Extension and OverridingCheckingAccount and SavingsAccount inherit the deposit() and withdraw().

CheckingAccount adds a new method, overdraftProtection() and overrides withdraw()

SavingsAccount adds a new method, annualInterest()

Show class CheckingAccount

Example1_22

Show class CheckingAccount

Example1_22

11 ACM/JETT Workshop - August 4-5, 2005

Overriding a Method• A subclass overrides a method contained

in its super class.

• Both methods should have the same signature.

• Overriding a method allows the subclass– to extend the method in the super-class and– Modify the behavior in the super class as

befits the context of the subclass.

12 ACM/JETT Workshop - August 4-5, 2005

Overriding a MethodExamplewithdraw( ) in super class BankAccount successfully withdraws the amount if the amount <= balance.

withdraw () in subclass CheckingAccount withdraws the amount if the amount <= balance or if the amount <= balance + overdraftProtection.

13 ACM/JETT Workshop - August 4-5, 2005

Inheritance

• private members in the super class are not accessible in the subclass.

• protected members in the super class

– Are accessible in the subclass.

– Are not accessible outside the package.

14 ACM/JETT Workshop - August 4-5, 2005

Inheritance – Some Examples

Car and Bicycle override the method move()

15 ACM/JETT Workshop - August 4-5, 2005

What is an abstract class?Let us look at the classes, Shape, Circle and

Rectangle, where Circle and Rectangle are both Shapes. We know that a shape has

area, but we do not know how to compute area unless we know what kind of concrete shape it is.

Then area() is an abstract method in class Shape.

The class Shape itself is an abstract class.

16 ACM/JETT Workshop - August 4-5, 2005

Abstract classes

• An abstract class cannot be instantiated (no objects can be created from this class).

• In Java, an abstract class must be declared with the abstract keyword.

• An abstract class can contain one or more abstract methods.

17 ACM/JETT Workshop - August 4-5, 2005

Abstract classes

• An abstract method has no method body (definition), just a declaration with method signature.

• Why have an abstract method?• An abstract method specifies a

responsibility that the derived (subclasses) classes should fulfill.

• The concrete subclasses of an abstract class define the inherited abstract methods.

18 ACM/JETT Workshop - August 4-5, 2005

Abstract classes and abstract methods

The area() in Shape class is declared, but not defined. This is an abstract method.

Class Shape is an abstract class.

Circle and Rectangle define the area()

Show Shape classes Example2_22

Show Shape classes Example2_22

19 ACM/JETT Workshop - August 4-5, 2005

Mixing Object Types Assume we have a class Car and a class BankAccount.We have the following statements:

// Create an instance of a CarCar myCar = new Car();

// Declare a variable of type BankAccount:BankAccount myAcct;

//Assign myCar to myAcct.

myAcct = myCar; //A compile-time error.

Why?

20 ACM/JETT Workshop - August 4-5, 2005

Mixing Object Types

myAcct = myCar; The object types do not match in the

assignment statement.

21 ACM/JETT Workshop - August 4-5, 2005

Mixing Object TypesLet us look at a slightly different situation:

CheckingAccount cAcct = new CheckingAccount ();

BankAccount myAcct;

myAcct = cAcct;This assignment is OK, since an instance of a

CheckingAccount is also of type BankAccount because (CheckingAccount is-a BankAccount).

What is the rule?

22 ACM/JETT Workshop - August 4-5, 2005

SubstitutabilityA variable defined to be of type base class

can reference an object of any of the derived classes.

Therefore, the following assignments are ok.

BankAccount myAcct;

myAcct = new CheckingAccount();

myAcct = new SavingsAccount();

23 ACM/JETT Workshop - August 4-5, 2005

SubstitutabilityIs the following assignment ok? Here, we are assigning a variable of base

class type to a variable of type derived class.

CheckingAccount cAcct;

cAcct = new BankAccount();

This will give a compile-time error.

24 ACM/JETT Workshop - August 4-5, 2005

Substitutability

Given the Shape classes, are these following statements legal?

Shape shape1 = new Shape();

shape1 = new Circle();

shape1 = new Rectangle();

Shape [] someShapes = new Shape[3];

someShapes[0] = new Circle(5);

someShapes[1] = new Rectangle(5,10);

25 ACM/JETT Workshop - August 4-5, 2005

Object – the ancestor of all Java classes • All classes in Java inherit from one

common super class named Object.• The Object class defines a set of basic

methods that all Java classes may need.• Some of these are:

– clone()– equals()– toString()

• Classes typically override these methods to implement their specific functionality.

26 ACM/JETT Workshop - August 4-5, 2005

Java interfaces

27 ACM/JETT Workshop - August 4-5, 2005

Interfaces

• An interface in Java is a “strict abstract class” with only

– Method declarations

– No method definitions ie. no implementations.

– Can also contain constants

• You cannot create an object from an interface.

28 ACM/JETT Workshop - August 4-5, 2005

Interfaces

• A class can implement an interface (s).

• When a class implements an interface, it should provide definitions for all methods declared in the interface.

• One interface can extend another, but

– An interface cannot extend a class

– A class cannot extend an interface

– Classes implement an interface

29 ACM/JETT Workshop - August 4-5, 2005

Defining Interfaces

Define an interface called Taxable

public interface Taxable {// A constantpublic static final double

TAX_RATE = 0.1;// A method declarationpublic double computeTax();

}

30 ACM/JETT Workshop - August 4-5, 2005

Implementing interfaces Class Stock implements the interface Taxable

public class Stock extends Asset implements Taxable

{ public double computeTax(){

return ((stockPrice * numberOfStocks) * Taxable.TAX_RATE)

}

private double stockPrice;

private int numberOfStocks;

}

31 ACM/JETT Workshop - August 4-5, 2005

Benefits of Interfaces

• Separates a specification from an implementation.

• A Java interface is also a Java type.

• Is someStock of type Stock? Yes.

• Is someStock of type Taxable? Yes, since class Stock implements Taxable interface.

Stock someStock = new Stock();

32 ACM/JETT Workshop - August 4-5, 2005

Some Commonly used Java interfaces

• Clonable

• Serializable

• Comparable, …

33 ACM/JETT Workshop - August 4-5, 2005

Dynamic Binding

• For this discussion we will again use the BankAccount classes.

34 ACM/JETT Workshop - August 4-5, 2005

Static vs Dynamic Binding

• Suppose we have the following code:

CheckingAccount c1 = new CheckingAccount();

• What is the type of the reference variable c1?• It is CheckingAccount, as determined at compile

time. • CheckingAccount is called the variable’s static

type.

35 ACM/JETT Workshop - August 4-5, 2005

Static vs Dynamic Binding

• Static binding is done by the compiler when it can determine the type of an object

c1.withdraw();

This call to the withdraw() method will be bound to the withdraw() defined in class CheckingAccount.

36 ACM/JETT Workshop - August 4-5, 2005

Static vs Dynamic Binding

Now,let us change the code to the following:

BankAccount b;

b = new CheckingAccount();• Is this assignment ok? Yes.• What is the type of the reference variable b?• It’s static type is BankAccount, as determined at

compile time. • Its dynamic type is CheckingAccount as

determined at runtime.

37 ACM/JETT Workshop - August 4-5, 2005

Static vs Dynamic Binding

BankAccount b;

b = new CheckingAccount();

b.withdraw();

Is the call to the method, withdraw() result in execution of withdraw() in BankAccount or withdraw() in CheckingAccount?

It will result in dynamically binding to

CheckingAccount.withdraw().

38 ACM/JETT Workshop - August 4-5, 2005

Static vs Dynamic Binding

The Rule: • Whenever a reference refers to an

interface or a base class, methods are dynamically bound

• Dynamic Binding is method implementation determined at runtime.

• Also known as Polymorphism

39 ACM/JETT Workshop - August 4-5, 2005

Checking an Object’s Type• Its possible to check the actual type of an

object using the instanceof operator.

Example

BankAccount myAcct;

myAcct = new CheckingAccount();

If (myAcct instanceof CheckingAccount )

….

40 ACM/JETT Workshop - August 4-5, 2005

ExerciseConsider the classes below:

41 ACM/JETT Workshop - August 4-5, 2005

Exercise• Given the interface and classes on the

previous slide, are these following statements valid?

Taxable [] assets = new Taxable[5];assets[0] = new Stock();assets[1] = new RealEstate();..

for (int i = 0;i < assets.length; ++i)

double d = assets[i].computeTax();

42 ACM/JETT Workshop - August 4-5, 2005

Casting

We know the following assignment is OK.

Taxable oneAsset = new Stock();

oneAsset.computeTax(); // Ok

oneAsset.getStockPrice();// Not Ok// Cast it to Stock and then call

// method

if (oneAsset instanceof Stock)

((Stock)oneAsset).getStockPrice();

43 ACM/JETT Workshop - August 4-5, 2005

Test your Understanding• What is inheritance for?• What is overriding a method?• Can I assign an instance of a subclass to a variable of

type super class? Or, vice versa?• What is an abstract class?• What is an abstract method?• What is an interface?• What is dynamic binding?• What is casting?

You will get some hands-on experience in using some of these features in Lab 3