OOP in Java : © W. Milner 2005 : Java and OOP Part 3 – Extending classes
Dec 30, 2015
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.
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
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
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:
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("=========================");}
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;}
OOP in Java : © W. Milner 2005 : Slide 8
Implementation of Perishable
public class Perishable extends Product{
public void deliver(int howMany) { stockLevel=howMany; }
}
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;}
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====================
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
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..
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;}
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
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.
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..
OOP in Java : © W. Milner 2005 : Slide 17
Object example
Object someObject= new Object();System.out.println(someObject);
Output:java.lang.Object@187c6c7
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
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..
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
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
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
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..
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
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;}
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(); } }}
OOP in Java : © W. Milner 2005 : Slide 27
Using the subclass
Rectangle r = new Rectangle(4,5);r.draw();