1 / 28

Java and OOP

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.

Download Presentation

Java and OOP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java and OOP Part 3 – Extending classes

  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.

  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

  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

  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:

  6. Product class definition public 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("========================="); }

  7. public boolean needMore() { if (stockLevel==0) return true; else return false; } public void sell(int howMany) { stockLevel-=howMany; if (stockLevel<0) stockLevel=0; } Rest of Product public int getStockLevel() { return stockLevel; } private static int lastBarcodeUsed=0; private int barcode; protected int stockLevel; } public void deliver(int howMany) { if (howMany<0) { System.out.println("Invalid delivery"); return; } else stockLevel+=howMany; }

  8. Implementation of Perishable public class Perishable extends Product { public void deliver(int howMany) { stockLevel=howMany; } }

  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; }

  10. public 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();} } Using the subclass All 3 use default constructor =stocklevel 100 Barcode = 1 Stocklevel = 200 ==================== Barcode = 2 Stocklevel = 50 ==================== Barcode = 3 Stocklevel = 60 ====================

  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

  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..

  13. Using super() public Perishable(int initStock, int initLocationCode) { super(initStock); locationCode = initLocationCode; } public Product(int initStockLevel) { barcode=lastBarcodeUsed++; stockLevel=initStockLevel; }

  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

  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.

  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..

  17. Object example Object someObject= new Object(); System.out.println(someObject); Output: java.lang.Object@187c6c7

  18. Changing and using toString In Perishable definition.. .. public String toString() { return "Perishable ID="+barcode+" Loc="+locationCode+" stock="+stockLevel; } .. 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 Output: Perishable ID=0 Loc=30 stock=20 Perishable ID=1 Loc=45 stock=20

  19. final methods • A method declared as final in a superclass cannot be altered in a subclass • For example..

  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

  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 final public void display() ^ 1 error

  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

  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..

  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

  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; }

  26. 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(); } } } Subclass of abstract class

  27. Using the subclass Rectangle r = new Rectangle(4,5); r.draw();

  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?

More Related