1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

download 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

of 68

Transcript of 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    1/68

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    2/68

    Contents

    1. Inheritance in Java Inheriting Classes The super Reference Overriding Methods Polymorphism The instanceof Operator final Methods and Classes

    2

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    3/68

    Contents (2)

    1. Abstract Classes Abstract Methods

    2. Interfaces Defining Interfaces Implementing Interfaces

    3. Using Interfaces (Demo)

    3

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    4/68

    Access Modifierspublic, private, protected, default

    (package)

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    5/68

    Access Modifiers

    The most common modifiers are the accessmodifiers:

    public

    private protected (default)

    Access modifiers control which classesmay use a member

    5

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    6/68

    Access Modifiers Rules

    The variables that you declare and usewithin a classs methods may not haveaccess modifiers

    The only access modifier permitted to non-inner classes is public A member may have at most one access

    modifier

    6

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    7/68

    public

    The most generous access modifier is public A public class, variable, or method may be

    used in any Java program withoutrestriction Any public method may be overridden by

    any subclass

    7

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    8/68

    private

    The least generous access modifier is private Top-level (that is, not inner) classes may

    not be declared private A private variable or method may be used

    only by an instance of the class thatdeclares the variable or method

    8

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    9/68

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    10/68

    (default)

    Default is the name of the access ofclasses, variables, and methods if youdont specify an access modifier

    A classs data and methods may be default,as well as the class itself

    A classs default members are accessible toany class in the same package as the class

    in question A default method may be overridden by any

    subclass that is in the same package as thesuperclass 10

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    11/68

    Applying Encapsulation inJava

    Instance variables should bedeclared as private

    Only instance methods can

    access private instancevariables

    Movie mov1 = new Movie();String rating = mov1.getRating();String r = mov1.rating; // Error: private

    ...if (rating.equals("G"))

    var

    aMethod

    aMethod()

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    12/68

    Packages

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    13/68

    What Are Java Packages?

    A package is a container of classes that arelogically related A package consists of all the Java classes

    within a directory on the file system Package names and used within a JRE to

    manage the uniqueness of identifiers They segment related parts of complex

    applications into manageable parts

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    14/68

    Grouping Classes in aPackage

    Include the package keyword followed byone or more names separated by dots at thetop of the Java source file

    If omitted the compiler places the class inthe default unnamed package 14

    package utils;

    public class MathUtils {...

    }

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    15/68

    Grouping Classes in aPackage

    To run a main() method in a packaged classrequires: The CLASSPATH to contain the directory

    having the root name of the package tree The class name must be qualified by its

    package name

    15

    java cp . myPackage.MainClass

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    16/68

    The CLASSPATH withPackages

    Includes the directory containing the top levelof the package tree

    16C:\>setCLASSPATH=E:\Curriculum\courses\java\practices\les06

    Package name .class location

    CLASSPATH

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    17/68

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    18/68

    Inheritance andPolymorphismCode Reuse Techniques

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    19/68

    Key Object-OrientedComponents

    InheritanceConstructors referenced by subclass

    Polymorphism

    Inheritance is an OO fundamental

    InventoryItem

    Movie Game Book

    Superclass

    Subclasses

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    20/68

    Example of Inheritance

    The InventoryItem class defines methodsand variables

    Movie extends InventoryItem and can:

    Add new variables

    Add new methods

    Override methods in InventoryItem class

    InventoryItem

    Movie

    f h

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    21/68

    Specifying Inheritance inJava

    Inheritance is achieved by specifying whichsuperclass the subclass extends

    Movie inherits all the variables and methodsof InventoryItem

    public class InventoryItem {

    }

    public class Movie extends InventoryItem {

    }

    Wh D S b l

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    22/68

    What Does a SubclassObject Look Like?

    A subclass inherits all the instancevariables of its superclass

    Movie

    titlelength

    pricecondition

    public class Movie extends InventoryItem {

    private String title; private int length;

    }

    public class InventoryItem {

    private float price; private String condition;

    }

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    23/68

    Default Initialization

    What happens when asubclass object is created?

    If no constructors are defined:

    First, the defaultparameterless constructor is

    called in the superclass

    Then, the defaultparameterless constructor is

    called in the subclass

    Movie movie1 = new Movie();

    Movie

    titlelength

    pricecondition

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    24/68

    The super Reference

    Refers to the base classIs useful for calling base classconstructors

    Must be the first line in the derived classconstructor

    Can be used to call any base class

    methods public class Movie extends InventoryItem {

    public Movie() {super("Matrix 8");

    }}

    h f

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    25/68

    The super ReferenceExample

    public class InventoryItem {InventoryItem(String cond) {

    System.out.println("InventoryItem");

    }}class Movie extends InventoryItem {

    Movie(String title) {super(title); System.out.println("Movie");

    }}

    Base classconstructor

    Calls baseclass

    constructor

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    26/68

    Using SuperclassConstructors

    Use super() to call a superclassconstructor: public class InventoryItem {

    InventoryItem(float p, String cond) {

    price = p;condition = cond;}

    public class Movie extends InventoryItem{

    Movie(String t, float p, String cond) {super(p, cond);title = t;

    }

    S if i Additi l

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    27/68

    Specifying AdditionalMethods

    The superclass defines methods for alltypes of InventoryItemThe subclass can specify additional

    methods that are specific to Movie public class InventoryItem {

    public float calcDeposit() public String calcDateDue()

    public class Movie extends InventoryItem { public void getTitle() public String getLength()

    O idi S l

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    28/68

    Overriding SuperclassMethods

    A subclass inherits all the methods of itssuperclass

    The subclass can override a method with itsown specialized version

    Must have the same signature and semanticsas the superclass method

    In Java all methods are virtual (unlessdeclared as final )

    This forces the l ate b ind ing mechanism oneach method call

    O idi g S l

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    29/68

    Overriding SuperclassMethods Example

    public class InventoryItem {

    public float calcDeposit(int custId) {return itemDeposit;

    }}

    public class Movie extends InventoryItem {

    public float calcDeposit(int custId) {if (specialCustomer(custId) {

    return itemDeposit / 2;} else {return itemDeposit;

    }}

    }

    I ki g S l

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    30/68

    Invoking SuperclassMethods

    If a subclass overrides a method, it can stillcall the original superclass method

    Use super.method() to call a superclassmethod from the subclass

    public class InventoryItem { public float calcDeposit(int custId) {

    if return 33.00;

    }

    public class Movie extends InventoryItem { public float calcDeposit(int custId) {

    itemDeposit = super.calcDeposit(custId);return (itemDeposit + vcrDeposit);

    }

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    31/68

    Acme Video and

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    32/68

    Acme Video andPolymorphism

    Acme Video started renting only videosAcme Video added games and VCRs

    Whats next?

    Polymorphism solves the problem

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    33/68

    ShoppingBasketvoid addItem(InventoryItem item) {

    // this method is called each time// the clerk scans in a new itemfloat deposit = item.calcDeposit();

    }

    InventoryItem

    VCR Movie

    calcDeposit(){}

    calcDeposit(){} calcDeposit(){}

    How It Works

    Using the instanceof

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    34/68

    Using the instanceof Operator

    The true type of an object can bedetermined by using an instanceof operator

    An object reference can be downcast to thecorrect type, if needed

    public void aMethod(InventoryItem i) {if (i instanceof Movie)

    ((Movie)i).playTestTape();}

    Limiting Methods and

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    35/68

    Limiting Methods andClasses with final

    A method can be marked as final to preventit from being overridden

    A whole class can be marked as final to

    prevent it from being extended public final class Color {

    }

    public final boolean checkPassword(String p) {

    }

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    36/68

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    37/68

    Abstract Classes andInterfaces

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    38/68

    Defining Abstract Classes

    Abstract classes model abstractconcepts from the real worldCannot be instantiated directly

    Should be subclasses to be instantiatedAbstract methods must be implementedby subclasses

    Abstractsuperclass

    Concretesubclasses

    InventoryItem

    Movie VCR

    Creating Abstract Classes

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    39/68

    Creating Abstract Classesin Java

    Use the abstract keyword to declare aclass as abstract

    public abstract class InventoryItem { private float price; public boolean isRentable()

    }

    public class Movieextends InventoryItem { private String title; public int getLength()

    public class Vcrextends InventoryItem { private int serialNbr; public void setTimer()

    What Are Abstract

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    40/68

    What Are AbstractMethods?

    An abstract method:Is an implementation placeholder

    Is part of an abstract class

    Must be overridden by a concrete subclass

    Each concrete subclass can implement themethod differently

    Defining Abstract Methods

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    41/68

    Defining Abstract Methodsin Java

    Use the abstract keyword to declare a methodas abstract :

    Provide the method signature only

    The class must also be abstract

    Why is this useful?

    Declare the structure of a class withoutproviding complete implementation of everymethod

    public abstract class InventoryItem { public abstract boolean isRentable();

    Defining and Using

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    42/68

    Defining and UsingInterfaces

    An interface is like a fully abstract class:All of its methods are abstract

    All variables are public static final

    An interface lists a set of method signatures,without any code details

    A class that implements the interface must

    provide code details for all the methods ofthe interface

    A class can implement many interfaces butcan extend only one class

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    43/68

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    44/68

    Creating an Interface

    Use interface keyword

    All methods public abstractAll variables public static final

    public interface Steerable {int MAXTURN_DEGREES = 45;void turnLeft(int deg);void turnRight(int deg);

    }

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    45/68

    Implementing an Interface

    Use implements keyword

    public class Yacht extends Boatimplements Steerable

    public void turnLeft(int deg) {} public void turnRight(int deg) {} }

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    46/68

    Sort: A Real-World Example

    Is used by a number of unrelated classesContains a known set of methods

    Is needed to sort any type of objects

    Uses comparison rules known only to thesortable object

    Supports good code reuse

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    47/68

    Overview of the Classes

    Created by the sort expert:

    Created by the movie expert:

    public class

    MovieSortApplication

    public class Movie

    implements Sortable

    public interfaceSortable

    public classSort

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    48/68

    MyApplication passesan array of movies to

    Sort.sortObjects()1

    23sortObjects() asks amovie to compare itself

    with another movie

    The movie returnsthe result of the

    comparison

    4sortObjects()

    returns thesorted list

    Sort

    Movie

    MyApplication

    How the Sort Works?

    e Sortable

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    49/68

    e Sortable Interface

    Specifies the compare() method public interface Sortable {

    // compare(): Compare this object// to another object// Returns:// 0 if this object is equal to obj2// a value < 0 if this object < obj2// a value > 0 if this object > obj2int compare(Object obj2);

    }

    Th S Cl

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    50/68

    The Sort Class

    Implements sorting functionality: themethod sortObjects() public class Sort {

    public static void sortObjects(Sortable[] items) {// Perform "Bubble sort" algorithmfor (int i = 1; i < items.length; i++) {

    for (int j = 0; j < items.length-1; j++) {if (items[j].compare(items[j+1]) > 0) {

    Sortable tempItem = items[j+1];items[j+1] = items[j];

    items[j] = tempItem;}}

    }}

    }

    Th i Cl

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    51/68

    public class Movie extends InventoryItemimplements Sortable {

    private String title;

    public int compare(Object movie2) {String title1 = this.title;String title2 = ((Movie)movie2).getTitle();

    return(title1.compareTo(title2));}}

    Implements Sortable

    The Movie Class

    U i h S

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    52/68

    Using the Sort

    Call Sort.sortObjects(Sortable []) with an array of Movie as the argument

    public class MovieSortApplication {

    Movie[] movieList;

    public static void main(String[] args) {// Build the array of Movie objectsSort.sortObjects(movieList);

    }}

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    53/68

    Sorting with Interfaces

    Live Demo

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    54/68

    Inner Classes

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    55/68

    Defining Static Inner

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    56/68

    Defining Static InnerClasses

    public class Outer {

    private static float varFloat = 3.50f; private String varString; static class InnerStatic {

    }

    Defined at class level Can access only static members of the outer

    class

    Defining Member Inner

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    57/68

    Defining Member InnerClasses

    public class Outer {

    private static float varFloat = 3.50f; private String varString;

    ...class InnerMember {

    ...Outer.this

    ...

    }

    Defined at class level Instance of the outer is needed Keyword this used to access the outer instance

    Defining Local Inner

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    58/68

    gClasses

    Are defined at the method level Are declared within a code block Have access only to final variables

    Cannot have a constructor public class Outer {

    ... public void outerMethod(final int var1){

    final int var2=5; ...

    class InnerLocal { private int localVar = var1 + var2; ...}}

    }

    Defining Anonymous Inner

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    59/68

    g yClasses

    Defined at method level Declared within a code block Missing the class , extends , and

    implements keywords Cannot have a constructor

    public class Outer { public void outerMethod(){

    myObject.myAnonymous(new SomeClass(){...} )

    }}

    Using instanceof with

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    60/68

    g instanceofInterfaces

    Use the instanceof operator to check ifan object implements an interface

    Use downcasting to call methods definedin the interface

    public void aMethod(Object obj) {if (obj instanceof Sortable) {

    result = ((Sortable)obj).compare(obj2); }

    }

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    61/68

    Cl Di g E l

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    62/68

    Class Diagrams Example

    62

    Shape

    #mPosition:Point

    structPoint

    +mX:int+mY:int

    +Point

    interfaceISurfaceCalculatable

    +CalculateSurface:int

    Rectangle

    -mWidth:int-mHeight:int

    +Rectangle+CalculateSurface:int

    Square

    -mSize:int

    +Square+CalculateSurface:int

    FilledSquare

    -mColor:Color

    +FilledSquare

    structColor

    +mRedValue:byte+mGreenValue:byte+mBlueValue:byte

    +Color

    FilledRectangle

    -mColor:Color

    +FilledRectangle

    Inheritance and Polymorphism

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    63/68

    Questions?

    Inheritance and Polymorphism

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    64/68

    Problems

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    65/68

    Problems

    1. Inherit from the base abstract class Cat andcreate subclasses Kitten and Tomcat . Theseclasses should fully implement the IAnimal interface and define an implementation for the

    abstract methods from the class Cat .2. Write a class TestAnimals that creates an

    array of animals ( IAnimal[] ): Dog, Frog ,Kitten , Tomcat and calls their methodsthrough IAnimal interface to ensure theclasses are implemented correctly.

    65

    Homework

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    66/68

    Homework

    1. Create a class diagram for the hierarchyIAnimal , Dog, Frog , Cat , Kitten , Tomcat .

    66

    Problems

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    67/68

    Problems

    1. Create a project, modeling a restaurantsystem. You need to model the Restaurant,People (Personnel and Clients), Orders from aclient and Products for orders. Products could

    be Meals or Beverages.2. Client has one order and could buy many

    products. Orders are limited to a maximumbill. No products could be added above themaximum.

    3. Clients could pay with tip included (bill = price+ tip) 67

    Problems

  • 8/11/2019 1 6inheritance and Polymorphism v0!9!101027034323 Phpapp02

    68/68

    Problems

    1. Tasks: Model the scheme and conventions Find the top 5 clients with largest bills

    Sort clients by name in a collection Design a function to find the day revenue of

    the restaurant

    Find the waiter with most tips

    68