Вы находитесь на странице: 1из 31

Java Methods

A & AB
Object-Oriented Programming and Data Structures
Maria Litvin Gary Litvin
11
A

Chap

Apt

Chapter

Class Hierarchies and Interfaces


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

Objectives:
Understand class hierarchies and
polymorphism

Learn about abstract classes Learn the syntax for calling superclasss
constructors and methods

Understand interfaces

11-2

Inheritance
Superclass (Base class)
Subclass extends Superclass

Subclass (Derived class)

Inheritance represents the IS-A relationship


between objects: an object of a subclass IS-A(n) object of the superclass.
11-3

Class Hierarchies
Using inheritance, a programmer can define a
hierarchy of classes.
Biped Walker ToedInWalker Hopper Dancer

CharlieChaplin

11-4

Class Hierarchies (contd)


Help reduce duplication
of code by factoring out common code from similar classes into a common superclass.
Walker Constructor firstStep nextStep stop distanceTraveled Biped Constructor Accessors turnLeft turnRight turnAround draw Hopper Constructor firstStep nextStep stop distanceTraveled
11-5

Class Hierarchies (contd)


Help reduce duplication of code by letting you
write more general methods in client classes.
public void moveAcross

(Walker
{

creature, int distance)

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

Works for either Walker or Hopper due to polymorphism

creature.nextStep(); creature.stop();
} 11-6

Polymorphism
Ensures that the correct method is called for
an object of a specific type, even when that object is disguised as a reference to a more generic type, that is, the type of the objects superclass or some ancestor higher up the inheritance line.

Once you define a common superclass,

polymorphism is just there no need to do anything special.

11-7

Polymorphism (contd)
The actual parameter passed to this method can be a Walker, a Hopper, etc. any subclass of Biped. public void moveAcross (Biped creature, int distance) { creature.firstStep(); while (creature.distanceTraveled () < distance) creature.nextStep(); creature.stop(); } Correct methods will be called automatically for any specific type of creature: Walkers methods for Walker, Hoppers for Hopper, etc.
11-8

Abstract Classes
Some of the methods in a class can be
declared abstract and left with only signatures defined

A class with one or more abstract methods


must be declared abstract
public abstract class Biped { ... public abstract void firstStep(); public abstract void nextStep(); public abstract void stop(); ... public void draw(Graphics g) { ... } }

Abstract methods

11-9

Abstract Classes (contd)


Abstract classes serve as common
superclasses for more specific classes

An abstract method provides an opportunity


for the compiler to do additional error checking

Abstract classes and methods are needed for


polymorphism to work

Abstract classes are closer to the root of the


hierarchy; they describe more abstract objects
11-10

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)

11-11

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 concrete

A class with no abstract methods is called

11-12

Class Object
In Java every class by default extends a
library class Object (from java.lang)

Object is a concrete class


public class Object { public String toString {...} public boolean equals (Object other) {... } public int hashCode() { ... }
// a few other methods ... }

Methods redefined (overridden) as necessary

11-13

Calling Superclasss Constructors

Biped Walker

public class Walker extends Biped { // Constructor public Walker(int x, int y, Image leftPic, Image rightPic) { Calls Bipeds super(x, y, leftPic, rightPic); ... constructor } The number / types of parameters passed to } super must match parameters of one of the
If present, must be the first statement superclasss constructors.

11-14

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 by default.
Must be defined then. If not defined syntax error: cannot find symbol : constructor ...

11-15

Calling Superclasss Constructors (contd)


Superclasss constructor calls its superclasss
constructor, and so on, all the way up to Objects constructor.
Object
super( )

Biped
super(...)

Walker
11-16

Calling Superclasss Methods

Walker CharlieChaplin

public class CharlieChaplin extends Walker { ... public void nextStep () { turnFeetIn(); Calls Walkers super.nextStep(); nextStep turnFeetOut(); } ... super.someMethod refers to someMethod in } the nearest class, up the inheritance line, where someMethod is defined.
11-17

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); ... } ...
11-18

Interfaces
DanceFloor
DanceGroup ControlPanel Band Dancer
Interface

Aerobics
Waltz Rumba Cha-Cha-Cha Salsa

Dance

11-19

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 interface Dance { DanceStep getStep (int i); int getTempo (); int getBeat (int i); }

public abstract is not written because all the


methods are public abstract.
11-20

Interfaces (contd)
We must officially state that a class
implements 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) { ... } ... }
11-21

Interfaces (contd)
A class can implement several interfaces. Like an abstract class, an interface supplies a
secondary data type to objects of a class that implements that interface.

You can declare variables and parameters of


an interface type.
Dance d = new Waltz( );

Polymorphism fully applies to objects


disguised as interface types.
11-22

Interfaces (contd)
public interface Edible { String getFoodGroup(); int getCaloriesPerServing(); } public class Pancake implements Edible { ... }

public class Breakfast Polymorphism: { the correct private int myTotalCalories = 0; method is called ... for any specific public void eat (Edible obj, int servings) type of Edible, { e.g., a Pancake myTotalCalories += obj.getCaloriesPerServing () * servings; } ... }
11-23

Classes
Similarities

Interfaces
An interface provides a
secondary data type to objects of classes that implement that interface.

A superclass provides a
secondary data type to objects of its subclasses.

An abstract class
cannot be instantiated.

An interface cannot be
instantiated.

11-24

Classes
Similarities

Interfaces
A concrete class that
implements an interface must define all the methods specified by the interface.

A concrete subclass of
an abstract class must define all the inherited abstract methods.

A class can extend


another class. A subclass can add methods and override some of its superclasss methods.

An interface can extend


another interface (called its superinterface) by adding declarations of abstract methods.
11-25

Classes
Differences

Interfaces
A class can implement
any number of interfaces.

A class can extend only


one class.

A class can have fields.

An interface cannot
have fields (except, possibly, some public static final constants).

A class defines its own


constructors (or gets a default constructor).

An interface has no
constructors.
11-26

Classes
Differences

Interfaces
All methods declared in
an interface are abstract.

A concrete class has all


its methods defined. An abstract class usually has one or more abstract methods.

Every class is a part of


a hierarchy of classes with Object at the top.

An interface may
belong to a small hierarchy of interfaces, but this is not as common.
11-27

Dance Studio

DanceStudio DanceLesson ControlPanel

interface

StudentGroup DanceFloor DanceGroup

Band

interface

Biped

Dancer

Dance

Foot

DanceStep

AbstractDance

CoordinateSystem
depends on extends

< various dances >

implements has

11-28

Review
Describe two ways for eliminating duplicate
code using class hierarchies.

What is an abstract class? Why is it better to use an abstract method


rather than an empty method?

Define concrete class. What happens when a constructor of a


subclass does not have a super statement? Is superclasss constructor called?
11-29

Review (contd)
Can an abstract class be instantiated? Can someMethod1 have a call
super.someMethod2 ( )?

What happens if, by mistake, a programmer


puts in his paintComponent method a call paintComponent(g); instead of super.paintComponent(g);

?
11-30

Review (contd)
What is the main difference between an
abstract class and an interface?

Can a class implement several interfaces? Suppose you declare a variable of an


interface type. What type of value can be assigned to that variable?

What is the main advantage of interfaces over


abstract classes?

11-31

Вам также может понравиться