inheritance

22
Inheritance

Upload: daman-toor

Post on 15-Jul-2015

254 views

Category:

Education


0 download

TRANSCRIPT

Inheritance

In the Java language, classes can be derived from other classes, therebyinheriting fields and methods from those classes.

A class that is derived from another class is called a subclass (also a derivedclass, extended class, or child class).

The class from which the subclass is derived is called a superclass (also abase class or a parent class).

The idea of inheritance is simple but powerful:

When you want to create a new class and there is already a class that includessome of the code that you want, you can derive your new class from the existingclass.

In doing this, you can reuse the fields and methods of the existing class withouthaving to write (and debug!) them yourself.

A subclass inherits all the members (fields, methods, and nested classes) from itssuperclass.

Constructors are not members, so they are not inherited by subclasses, but theconstructor of the superclass can be invoked from the subclass.

The Java Platform Class Hierarchy

At the top of the hierarchy, Object is the most general of all classes. Classes near the bottom of the

hierarchy provide more specialized behavior.

All Classes in the Java Platform are Descendants of Object

An Example of Inheritance

public class Bicycle {

// the Bicycle class has three fieldspublic int cadence;public int gear;public int speed;

// the Bicycle class has one constructorpublic Bicycle(int startCadence,

int startSpeed, int startGear) {gear = startGear;cadence = startCadence;speed = startSpeed;

}

// the Bicycle class has four methodspublic void setCadence(int newValue) {

cadence = newValue;}

public void setGear(int newValue) {gear = newValue;

}

public void applyBrake(int decrement) {speed -= decrement;

}

public void speedUp(int increment) {speed += increment;

}

}

A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:

public class MountainBike extends Bicycle {

// the MountainBike subclass adds one fieldpublic int seatHeight;

// the MountainBike subclass has one constructorpublic MountainBike(int startHeight,

int startCadence,int startSpeed,int startGear) {

super(startCadence, startSpeed, startGear);seatHeight = startHeight;

}

// the MountainBike subclass adds one methodpublic void setHeight(int newValue) {

seatHeight = newValue;}

}

MountainBike inherits all the fieldsand methods of Bicycle and addsthe field seatHeight and a methodto set it.

Except for the constructor, it is as ifyou had written a newMountainBike class entirely fromscratch, with four fields and fivemethods.

However, you didn't have to do allthe work. This would be especiallyvaluable if the methods in theBicycle class were complex and hadtaken substantial time to debug.

A subclass inherits all of the public and protected members of its parent, no matter what

package the subclass is in. If the subclass is in the same package as its parent, it also

inherits the package-private members of the parent.

You can use the inherited members as is, replace them, hide them, or supplement them with

new members:

•The inherited fields can be used directly, just like any other fields.

•You can declare a field in the subclass with the same name as the one in the superclass,

thus hiding it (not recommended).

•You can declare new fields in the subclass that are not in the superclass.

•The inherited methods can be used directly as they are.

•You can write a new instance method in the subclass that has the same signature as the one

in the superclass, thus overriding it.

•You can write a new static method in the subclass that has the same signature as the one in

the superclass, thus hiding it.

•You can declare new methods in the subclass that are not in the superclass.

•You can write a subclass constructor that invokes the constructor of the superclass, either

implicitly or by using the keyword super.

What You Can Do in a Subclass

Private Members in a Superclass

A subclass does not inherit the private members of its parent class.

However, if the superclass has public or protected methods for accessing itsprivate fields, these can also be used by the subclass.

A nested class has access to all the private members of its enclosing class—bothfields and methods.

Therefore, a public or protected nested class inherited by a subclass has indirectaccess to all of the private members of the superclass.

Casting Objects

We have seen that an object is of the data type of the class from which it wasinstantiated. For example, if we write

public MountainBike myBike = new MountainBike();

then myBike is of type MountainBike.

MountainBike is descended from Bicycle and Object. Therefore, a MountainBike is aBicycle and is also an Object, and it can be used wherever Bicycle or Object objects arecalled for.

The reverse is not necessarily true: a Bicycle may be a MountainBike, but it isn'tnecessarily. Similarly, an Object may be a Bicycle or a MountainBike, but it isn'tnecessarily.

Casting shows the use of an object of one type in place of another type, among the objectspermitted by inheritance and implementations. For example, if we write

Object obj = new MountainBike();

then obj is both an Object and a MountainBike (until such time as obj is assigned anotherobject that is not a MountainBike). This is called implicit casting.

If, on the other hand, we write

MountainBike myBike = obj;

we would get a compile-time error because obj is not known to the compiler to be aMountainBike. However, we can tell the compiler that we promise to assign a MountainBiketo obj by explicit casting:

MountainBike myBike = (MountainBike)obj;

This cast inserts a runtime check that obj is assigned a MountainBike so that the compilercan safely assume that obj is a MountainBike. If obj is not a MountainBike at runtime, anexception will be thrown.

Note: You can make a logical test as to the type of a particular object using theinstanceof operator. This can save you from a runtime error owing to animproper cast. For example:

if (obj instanceof MountainBike) {MountainBike myBike = (MountainBike)obj;

}

Here the instanceof operator verifies that obj refers to a MountainBike so thatwe can make the cast with knowledge that there will be no runtime exceptionthrown.

Example

In this example, we can say that an Employee "is a kind of" Person.

An Employee object inherits all of the attributes, methods

and associations of Person

Person

- name: String

- dob: Date

Employee

- employeeID: int

- salary: int

- startDate: Date

Person

name = "John Smith"

dob = Jan 13, 1954

Employee

name = "Sally Halls"

dob = Mar 15, 1968

employeeID = 37518

salary = 65000

startDate = Dec 15,

2000

is a kind of

Inheritance in Java

Inheritance is declared using the "extends" keywordIf inheritance is not defined, the class extends a class called Object

Person

- name: String

- dob: Date

Employee

- employeeID: int

- salary: int

- startDate: Date

public class Person

{

private String name;

private Date dob;

[...]

public class Employee extends Person

{

private int employeID;

private int salary;

private Date startDate;

[...]

Employee anEmployee = new Employee();

Inheritance Hierarchy

Each Java class has one (and only one) superclass.C++ allows for multiple inheritance

Inheritance creates a class hierarchyClasses higher in the hierarchy are more general and more abstract

Classes lower in the hierarchy are more specific and concrete

ClassThere is no limit to the

number of subclasses a

class can have

There is no limit to the

depth of the class tree.

Class Class Class

Class

Class ClassClass

Constructors and Initialization

Classes use constructors to initialize instance variablesWhen a subclass object is created, its constructor is called.

It is the responsibility of the subclass constructor to invoke the

appropriate superclass constructors so that the instance variables

defined in the superclass are properly initialized

Superclass constructors can be called using the "super"

keyword in a manner similar to "this"

It must be the first line of code in the constructor

If a call to super is not made, the system will

automatically attempt to invoke the no-argument

constructor of the superclass.

Constructors - Example

public class BankAccount

{

private String ownersName;

private int accountNumber;

private float balance;

public BankAccount(int anAccountNumber, String aName)

{

accountNumber = anAccountNumber;

ownersName = aName;

}

[...]

}

public class OverdraftAccount extends BankAccount

{

private float overdraftLimit;

public OverdraftAccount(int anAccountNumber, String aName, float aLimit)

{

super(anAccountNumber, aName);

overdraftLimit = aLimit;

}

}

Method Overriding

Subclasses inherit all methods from their superclassSometimes, the implementation of the method in the superclass does

not provide the functionality required by the subclass.

In these cases, the method must be overridden.

To override a method, provide an implementation in the

subclass.The method in the subclass MUST have the exact same signature as

the method it is overriding.

Method overriding - Example

public class BankAccount

{

private String ownersName;

private int accountNumber;

protected float balance;

public void deposit(float anAmount)

{

if (anAmount>0.0)

balance = balance + anAmount;

}

public void withdraw(float anAmount)

{

if ((anAmount>0.0) && (balance>anAmount))

balance = balance - anAmount;

}

public float getBalance()

{

return balance;

}

}

Method overriding - Example

public class OverdraftAccount extends BankAccount

{

private float limit;

public void withdraw(float anAmount)

{

if ((anAmount>0.0) && (getBalance()+limit>anAmount))

balance = balance - anAmount;

}

}

Object References and Inheritance

Inheritance defines "a kind of" relationship.In the previous example, OverdraftAccount "is a kind of" BankAccount

Because of this relationship, programmers can

"substitute" object references.A superclass reference can refer to an instance of the superclass OR an

instance of ANY class which inherits from the superclass.

BankAccount anAccount = new BankAccount(123456, “ABC");

BankAccount account1 = new OverdraftAccount(3323, “XYZ",

1000.0);

anAccount

account1

BankAccount

name = “ABC"

accountNumber = 123456OverdraftAccount

name = “XYZ"

accountNumber = 3323

limit = 1000.0

Polymorphism

In the previous slide, the two variables are defined to

have the same type at compile time: BankAccountHowever, the types of objects they are referring to at runtime are

different

What happens when the withdraw method is invoked on

each object?anAccount refers to an instance of BankAccount. Therefore, the

withdraw method defined in BankAccount is invoked.

account1 refers to an instance of OverdraftAccount. Therefore, the

withdraw method defined in OverdraftAccount is invoked.

Polymorphism is: The method being invoked on an

object is determined AT RUNTIME and is based on the

type of the object receiving the message.

Final Methods and Final Classes

Methods can be qualified with the final modifierFinal methods cannot be overridden.

This can be useful for security purposes.

public final boolean validatePassword(String username, String Password)

{

[...]

Classes can be qualified with the final modifierThe class cannot be extended

This can be used to improve performance. Because there an be no

subclasses, there will be no polymorphic overhead at runtime.

public final class Color

{

[...]

Review

What is inheritance? What is a superclass? What is a

subclass?

Which class is at the top of the class hierarchy in Java?

What are the constructor issues surrounding inheritance?

What is method overriding? What is polymorphism? How

are they related?

What is a final method? What is a final class?