OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Object Oriented Programming with Java
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Inheritance // A simple class hierarchy. // A class for two-dimensional objects. class TwoDShape { double width; double height; void showDim() { System.out.println("Width.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
1. 2 Introduction to Inheritance  Access Modifiers  Methods in Subclasses  Method Overriding  Converting Class Types  Why up-cast?  Why down-cast?
1 CS2200 Software Development Polymorphism II A. O’Riordan, 2008 K. Brown,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Inheritance using Java
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
Intro to OOP with Java, C. Thomas Wu
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
What is inheritance? It is the ability to create a new class from an existing class.
CSC 142 Computer Science II Zhen Jiang West Chester University
Inheritance (Part 4) Abstract Classes 1.  sometimes you will find that you want the API for a base class to have a method that the base class cannot.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Some Object-Oriented Programming (OOP) Review. Let’s practice writing some classes Write an Employee class with methods that return values for the following.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance (Part 4) Polymorphism and Abstract Classes 1.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Coming up: Inheritance
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Topics Instance variables, set and get methods Encapsulation
OOP Basics Classes & Methods (c) IDMS/SQL News
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
1 More About Derived Classes and Inheritance Chapter 9.
Modern Programming Tools And Techniques-I
Ch 10- Advanced Object-Oriented Programming Features
Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Inheritance.
An Example of Inheritance
Chapter 11 Inheritance and Polymorphism Part 1
CS 240 – Advanced Programming Concepts
Presentation transcript:

OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes

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 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("========================="); }

OOP in Java : © W. Milner 2005 : Slide 7 Rest of Product public boolean needMore() { if (stockLevel==0) return true; else return false; } public void sell(int howMany) { stockLevel-=howMany; if (stockLevel<0) stockLevel=0; } 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 subclass 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();} } All 3 use default constructor =stocklevel 100 Barcode = 1 Stocklevel = 200 ==================== Barcode = 2 Stocklevel = 50 ==================== Barcode = 3 Stocklevel = 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:

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=20 Perishable 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 final public 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();

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?