class heir arc hies and interfaces

Upload: christi-dawydiak

Post on 05-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    1/31

    Class Hierarchies and Interfaces

    Java MethodsA & AB

    Object-Oriented Programmingand Data Structures

    Maria Litvin Gary Litvin

    Copyright 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

    11

    Chapter

    Chap Apt

    A

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    2/31

    11-2

    Objectives:

    Understand class hierarchies andpolymorphism

    Learn about abstract classes

    Learn the syntax for calling superclasssconstructors and methods

    Understand interfaces

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    3/31

    11-3

    Inheritance

    Inheritance represents the IS-A relationshipbetween objects: an object of a subclassIS-A(n) object of the superclass.

    Superclass(Base class)

    Subclass(Derived class)

    Subclass extendsSuperclass

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    4/31

    11-4

    Class Hierarchies

    Using inheritance, a programmer can define ahierarchy of classes.

    Biped

    Walker Hopper Dancer

    ToedInWalker CharlieChaplin

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    5/31

    11-5

    Class Hierarchies (contd)

    Help reduce duplicationof code by factoring outcommon code from

    similar classes into acommon superclass.

    BipedConstructorAccessorsturnLeftturnRightturnArounddraw

    Walker

    ConstructorfirstStepnextStepstopdistanceTraveled

    Hopper

    ConstructorfirstStepnextStepstopdistanceTraveled

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    6/31

    11-6

    Class Hierarchies (contd)

    Help reduce duplication of code by letting youwrite more general methods in client classes.

    public void moveAcross(Walker creature, int distance)

    {creature.firstStep();while (creature.distanceTraveled() < distance)

    creature.nextStep();creature.stop();

    }

    public void moveAcross(Hopper creature, int distance)

    {creature.firstStep();while (creature.distanceTraveled() < distance)

    creature.nextStep();creature.stop();

    }

    public void moveAcross(Biped creature, int distance)

    {creature.firstStep();while (creature.distanceTraveled() < distance)

    creature.nextStep();creature.stop();

    }

    Works for eitherWalker or Hopper

    due to polymorphism

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    7/3111-7

    Polymorphism

    Ensures that the correct method is called foran object of a specific type, even when thatobject is disguised as a reference to a more

    generic type, that is, the type of the objectssuperclass or some ancestor higher up theinheritance line.

    Once you define a common superclass,polymorphism is just there

    no need to do

    anything special.

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    8/3111-8

    Polymorphism (contd)

    public void moveAcross (Biped creature, int distance){creature.firstStep();while (creature.distanceTraveled () < distance)

    creature.nextStep();creature.stop();

    }

    The actual parameter passed to thismethod can be a Walker, a Hopper,etc. any subclass of Biped.

    Correct methods will be called automatically forany specific type of creature: Walkers methodsfor Walker, Hoppers forHopper, etc.

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    9/3111-9

    Abstract Classes

    Some of the methods in a class can bedeclared abstract and left with only signaturesdefined

    A class with one or more abstract methodsmust be declared abstract

    public abstract class Biped{

    ...public abstract void firstStep();public abstract void nextStep();public abstract void stop();...public void draw(Graphics g) { ... }

    }

    Abstractmethods

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    10/3111-10

    Abstract Classes (contd)

    Abstract classes serve as commonsuperclasses for more specific classes

    An abstract method provides an opportunity

    for the compiler to do additional errorchecking

    Abstract classes and methods are needed for

    polymorphism to work Abstract classes are closer to the root of the

    hierarchy; they describe more abstractobjects

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    11/3111-11

    Abstract Classes (contd)

    Object

    ... Component

    ... Button TextComponent Container

    ... JComponent Window

    ... JTextComponent AbstractButton JPanel ...

    ... JTextArea JTextField ... JMenuItem JButton ...

    A fragment of Java library GUI class hierarchy(abstract classes are boxed)

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    12/3111-12

    Abstract Classes (contd)

    Java does not allow us to instantiate (that is,create objects of) abstract classes

    Still, an abstract class can have constructors

    they can be called from constructors of

    subclasses

    A class with no abstract methods is calledconcrete

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    13/3111-13

    Class Object

    In Java every class by default extends alibrary class Object (fromjava.lang)

    Object is a concrete class

    public class Object{

    public String toString {...}public boolean equals (Object other) {... }public int hashCode() { ... }

    // a few other methods...

    }

    Methodsredefined(overridden)as necessary

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    14/3111-14

    Calling Superclasss

    Constructorspublic class Walker extends Biped{

    // Constructorpublic Walker(int x, int y, Image leftPic, Image rightPic){

    super(x, y, leftPic, rightPic);...

    }}

    Biped

    Walker

    Calls Bipedsconstructor

    If present, must bethe first statement

    The number / types of parameters passed tosuper must match parameters of one of thesuperclasss constructors.

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    15/31

    11-15

    Calling Superclasss

    Constructors (contd) One of the superclasss constructors is

    always called, but you dont have to have an

    explicit super statement. If there is no explicit call to super, then

    superclasss no-args constructor is called bydefault.

    Must be defined then. If not defined syntax error:cannot find symbol : constructor ...

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    16/31

    11-16

    Calling Superclasss

    Constructors (contd) Superclasss constructor calls its superclasss

    constructor, and so on, all the way up to

    Objects constructor.

    Biped

    Walker

    Objectsuper( )

    super(...)

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    17/31

    11-17

    Calling Superclasss

    Methodspublic class CharlieChaplin

    extends Walker

    {...public void nextStep (){

    turnFeetIn();

    super.nextStep();turnFeetOut();}

    ...}

    Walker

    CharlieChaplin

    Calls Walkers

    nextStep

    super.someMethodrefers to someMethod inthe nearest class, up the inheritance line, wheresomeMethod is defined.

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    18/31

    11-18

    Calling Superclasss

    Methods (contd) super. calls are often used in subclasses

    of library classes:

    public class Canvas extends JPanel{

    ...public void paintComponent (Graphics g)

    {super.paintComponent (g);...

    }...

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    19/31

    11-19

    Interfaces

    DanceFloor

    DanceGroup

    ControlPanel

    Band

    Dancer

    Aerobics

    Waltz

    Rumba

    Cha-Cha-Cha

    Salsa

    Dance

    Interface

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    20/31

    11-20

    Interfaces (contd)

    An interface in Java is like an abstract class,but it does not have any fields or constructors,and all its methods are abstract.

    public abstract is not written because all themethods are public abstract.

    public interface Dance{

    DanceStep getStep (int i);int getTempo ();int getBeat (int i);

    }

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    21/31

    11-21

    Interfaces (contd)

    We must officially state that a classimplements an interface.

    A concrete class that implements an interface

    must supply all the methods of that interface.public class Waltz implements Dance{

    ...// Methods:public DanceStep getStep (int i) { ... }public int getTempo () { return 750; }public int getBeat (int i) { ... }...

    }

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    22/31

    11-22

    Interfaces (contd)

    A class can implement several interfaces.

    Like an abstract class, an interface supplies asecondary data type to objects of a class that

    implements that interface. You can declare variables and parameters of

    an interface type.

    Polymorphism fully applies to objectsdisguised as interface types.

    Dance d = new Waltz( );

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    23/31

    11-23

    Interfaces (contd)public interface Edible{

    String getFoodGroup();int getCaloriesPerServing();

    }

    public class Breakfast{

    private int myTotalCalories = 0;...public void eat (Edible obj, int servings)

    {myTotalCalories +=

    obj.getCaloriesPerServing () * servings;

    }...

    }

    Polymorphism:the correctmethod is calledfor any specifictype of Edible,e.g., a Pancake

    public class Pancakeimplements Edible

    {...

    }

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    24/31

    11-24

    Classes Interfaces

    A superclass provides asecondary data type to

    objects of itssubclasses.

    An abstract classcannot be instantiated.

    An interface provides asecondary data type to

    objects of classes thatimplement thatinterface.

    An interface cannot beinstantiated.

    Similarities

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    25/31

    11-25

    Classes Interfaces

    A concrete subclass ofan abstract class mustdefine all the inherited

    abstract methods.

    A class can extend

    another class. Asubclass can addmethods and overridesome of its superclasss

    methods.

    A concrete class thatimplements an interfacemust define all the

    methods specified bythe interface.

    An interface can extend

    another interface (calledits superinterface) byadding declarations ofabstract methods.

    Similarities

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    26/31

    11-26

    Classes Interfaces

    A class can extend onlyone class.

    A class can have fields.

    A class defines its ownconstructors (or gets adefault constructor).

    A class can implementany number ofinterfaces.

    An interface cannothave fields (except,possibly, some publicstatic final constants).

    An interface has noconstructors.

    Differences

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    27/31

    11-27

    Classes Interfaces

    A concrete class has allits methods defined. Anabstract class usually

    has one or moreabstract methods.

    Every class is a part of

    a hierarchy of classeswith Object at the top.

    All methods declared inan interface areabstract.

    An interface may

    belong to a smallhierarchy of interfaces,but this is not ascommon.

    Differences

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    28/31

    11-28

    DanceStudio

    DanceStudio

    DanceFloor

    DanceGroup

    ControlPanel

    interfaceDanceDancerBiped

    Foot

    CoordinateSystem

    DanceStep

    A B

    extends

    depends on

    has

    implements

    Band

    DanceLesson

    interfaceStudentGroup

    < various dances>

    AbstractDance

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    29/31

    11-29

    Review

    Describe two ways for eliminating duplicatecode using class hierarchies.

    What is an abstract class?

    Why is it better to use an abstract methodrather than an empty method?

    Define concreteclass.

    What happens when a constructor of asubclass does not have a super statement?Is superclasss constructor called?

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    30/31

    11-30

    Review (contd)

    Can an abstract class be instantiated?

    Can someMethod1 have a callsuper.someMethod2 ( )?

    What happens if, by mistake, a programmerputs in his paintComponent method a call

    paintComponent(g);

    instead ofsuper.paintComponent(g);

    ?

  • 8/2/2019 Class Heir Arc Hies and Interfaces

    31/31

    11 31

    Review (contd)

    What is the main difference between anabstract class and an interface?

    Can a class implement several interfaces?

    Suppose you declare a variable of aninterface type. What type of value can beassigned to that variable?

    What is the main advantage of interfaces overabstract classes?