Top Banner
OOP in Java : © W. Milner 2005 : Java and OOP Part 3 – Extending classes
28

Java and OOP

Dec 30, 2015

Download

Documents

carol-osborn

Java and OOP. Part 3 – Extending classes. Inheritance. Suppose we want a version of an existing class, which is slightly different from it. We want to avoid starting again from scratch We can define the new class to be a sub-class of the first class. Terms used. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 1

Java and OOP

Part 3 – Extending classes

Page 2: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 2

Inheritance

Suppose we want a version of an existing class, which is slightly different from it.

We want to avoid starting again from scratch We can define the new class to be a sub-class

of the first class.

Page 3: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 3

Terms used

The original class is called the base class, the ancestor class or the super class

The process of designing the sub-class from the base class is called 'sub-classing' the base class

Page 4: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 4

Sub-classing

The subclass inherits all members and methods of the first

where needed we can write new versions of inherited methods – which replace the old method

we can add extra members and methods You can’t ‘loose’ a member or method No limit to levels of inheritance

Page 5: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 5

Example

Common type of sub-classing is specialization Suppose we want a type of product which is

perishable When we deliver new stock, we throw away

old stock – not add to it First review the Product class:

Page 6: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 6

Product class definitionpublic class Product{

public Product(){ lastBarcodeUsed++; barcode=lastBarcodeUsed; stockLevel=100;}

public Product(int initStock){ lastBarcodeUsed++; barcode=lastBarcodeUsed; stockLevel=initStock;}

public static int count(){ return lastBarcodeUsed;}

public void display(){ System.out.println("Barcode = "+barcode); System.out.println("Stocklevel = "+stockLevel); System.out.println("=========================");}

Page 7: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 7

Rest of Product

public void deliver(int howMany){ if (howMany<0) { System.out.println("Invalid delivery"); return; } else stockLevel+=howMany;}

public int getStockLevel(){ return stockLevel;}

private static int lastBarcodeUsed=0;private int barcode;protected int stockLevel;}

Page 8: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 8

Implementation of Perishable

public class Perishable extends Product{

public void deliver(int howMany) { stockLevel=howMany; }

}

Page 9: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 9

Protected

Problem – the deliver method in Perishable references the private field stockLevel – not allowed

Solution – use access control modifier protected Excerpt from modified Product definition –

..private static int lastBarcodeUsed=0;private int barcode;protected int stockLevel;}

Page 10: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 10

Using the subclasspublic class First{public static void main(String[] args){Product prod = new Product();prod.deliver(100);Perishable perish1 = new Perishable();Perishable perish2 = new Perishable();perish1.deliver(50);perish2.deliver(60);prod.display();perish1.display();perish2.display();}}

All 3 use default constructor =stocklevel 100Barcode = 1Stocklevel = 200====================Barcode = 2Stocklevel = 50====================Barcode = 3Stocklevel = 60====================

Page 11: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 11

Constructors of sub-classes

Constructors are not methods They are not inherited If you don't define one – the no-arg constructor

of the base class is called for you – see last example

Page 12: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 12

super()

super(); can be used as the first statement in a constructor

It means the corresponding superclass constructor is called

Further statements can take further action For example..suppose Perishable products

have an extra store location code..

Page 13: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 13

Using super()

public Perishable(int initStock, int initLocationCode){ super(initStock); locationCode = initLocationCode;}

public Product(int initStockLevel){ barcode=lastBarcodeUsed++; stockLevel=initStockLevel;}

Page 14: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 14

More on super()

super() cannot be anywhere except the first line of a constructor

If you don’t use super(), the system executes it anyway

IOW a subclass constructor first executes the no-arg constructor of the super class

Page 15: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 15

Exercise

Define an Employee class, with fields payrollNumber and rateOfPay

Define a Manager class as a sub-class of Employee. They are paid monthly – define their pay() method to display their pay

Define a Clerical class as a sub-class of Employee. They are hourly paid. Add an hoursWorked field, and a pay() method.

Page 16: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 16

Object

All classes descend from the class Object public class MyClass.. Is in effect: public class MyClass extends Object.. While if you say public class MyClass extends MySuperClass Then MySuperClass, or its ancestor, descends from Object Object objects have few useful methods Except toString(), which converts the object to a

descriptive string Which is what System.out.println calls For example..

Page 17: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 17

Object example

Object someObject= new Object();System.out.println(someObject);

Output:java.lang.Object@187c6c7

Page 18: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 18

Changing and using toString

In Perishable definition....public String toString(){ return "Perishable ID="+barcode+" Loc="+locationCode+" stock="+stockLevel;}..

Output:Perishable ID=0 Loc=30 stock=20Perishable ID=1 Loc=45 stock=20

in use..Perishable p1 = new Perishable(20,30);Perishable p2 = new Perishable(20,45);System.out.println(p1);System.out.println(p2);

calls toString() of Perishable objects

Page 19: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 19

final methods

A method declared as final in a superclass cannot be altered in a subclass

For example..

Page 20: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 20

Defining a method as final

In Product..public final void display(){ System.out.println("Barcode = "+barcode); System.out.println("Stocklevel = "+stockLevel); System.out.println("=========================");}

In Perishable..public void display(){ .. ..}

In use:Perishable p1 = new Perishable(20,30);Output on next slide

Page 21: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 21

Trying to override final - compile time error

C:\Walter\JavaProgs\Perishable.java:19: display() in Perishable cannot override display() in Product; overridden method is finalpublic void display() ^1 error

Page 22: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 22

Final classes – and why

A class declared as final cannot be subclassed Methods and classes are usually declared as

final for security Otherwise – a subclass of a standard

superclass might be defined, with.. Unpleasant overridden methods But at run-time a subclass object would look

like the superclass Eg the String class is final for this reason

Page 23: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 23

Abstract classes

Superclasses which are 'general' can be declared abstract

Used when subclasses will all implement the same method – in different ways, but

The superclass is too general to actually implement the method itself

For example..

Page 24: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 24

Example abstract class

Suppose we had a superclass called Shape And subclasses called Triangle, Rectangle,

Square and so on. Each would need a draw method But we could not program the draw method of

a Shape instance So the draw method of Shape is declared

abstract As is the class as a whole This means Shape cannot be instantiated

Page 25: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 25

Example abstract class

public abstract class Shape{

public Shape(int initHeight, int initWidth){

width=initWidth;height=initHeight;

}

public abstract void draw();

protected int width;protected int height;}

Page 26: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 26

Subclass of abstract class

public class Rectangle extends Shape{

public Rectangle(int h, int w){ super(h,w);}

public void draw() { for (int i=0; i<height; i++) { for (int j=0; j<width; j++)

System.out.print("*"); System.out.println(); } }}

Page 27: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 27

Using the subclass

Rectangle r = new Rectangle(4,5);r.draw();

Page 28: Java and OOP

OOP in Java : © W. Milner 2005 : Slide 28

Exercise

Copy the Shape class Define a Triangle class by subclassing Shape –

define the draw method How would you deal with a Square class?