Java Methods 3rd AP edition

Download Report

Transcript Java Methods 3rd AP edition

Java Methods

Object-Oriented Programming and Data Structures

3rd AP edition Maria Litvin ● Gary Litvin «

Interface

»

Chapter

Chapter12

Class Hierarchies and Interfaces

Copyright © 2015 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 superclass’s constructors and methods • Understand interfaces 12-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.

12-3

Class Hierarchies

• Using inheritance, a programmer can define a hierarchy of classes.

Balloon RoundBalloon SquareBalloon FancyBalloon BirthdayBalloon HotAirBalloon 12-4

Class Hierarchies (cont’d)

• Help reduce duplication of code by factoring out common code from similar classes into a common superclass.

Balloon Constructors Accessors

distance move setRadius isInside isOnBorder draw

RoundBalloon Constructor

draw (redefined)

OvalBalloon Constructor

distance (redefined) draw (redefined)

12-5

Class Hierarchies (cont’d)

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

} { public void

add (RoundBalloon b)

balloons.add(b); } { public void

add (OvalBalloon b)

balloons.add(b); Works for a any kind of

Balloon

} { public void

add (Balloon b)

balloons.add(b); 12-6

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 Abstract method { public

abstract

class Balloon ...

public

abstract

void draw (Graphics g, boolean makeItFilled)

;

12-7

Abstract Classes (cont’d)

• 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 are closer to the root of the hierarchy; they describe more abstract objects 12-8

Abstract Classes (cont’d)

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) 12-9

Abstract Classes (cont’d)

• • 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 called

concrete

12-10

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() { ... } Methods redefined (overridden) as necessary } // a few other methods ...

12-11

Invoking Superclass’s Constructors

RoundBalloon BirthdayBalloon } { public class

BirthdayBalloon extends RoundBalloon

{ // Constructor public

BirthdayBalloon

(int x, int y, int r, Color c, int age)

super

(x, y, r, c); this.age = age; Calls

RoundBalloon

constructor ’s } If present, must be the first statement The number / types of parameters passed to

super

must match parameters of one of the superclass’s constructors.

12-12

Invoking Superclass’s Constructors (cont’d)

• One of the superclass’s constructors is always called, but you don’t have to have an explicit

super

statement.

• If there is no explicit call to

super

, then superclass’s no-args constructor is called by default.

Must be defined then. If not defined  syntax error:

cannot find symbol : constructor ...

12-13

Invoking Superclass’s Constructors (cont’d)

• Superclass’s constructor calls its superclass’s constructor, and so on, all the way up to

Object

’s constructor.

Object super( ) Balloon super( ) RoundBalloon super( ) BirthdayBalloon 12-14

Calling Superclass’s Methods

RoundBalloon BirthdayBalloon } { public class BirthdayBalloon

extends RoundBalloon

{ ... public void

draw

(Graphics g, boolean makeItFilled) g.setFont (ageFont);

super.draw (g, makeItFilled);

Calls

RoundBalloon

’s

draw

g.setColor (Color.BLACK); g.drawString("" + age, getX() - 10, getY()); }

super.someMethod

refers to

someMethod

nearest class, up the inheritance line, where in the

someMethod

is defined.

12-15

Calling Superclass’s Methods (cont’d)

• super -dot calls are often used in subclasses of library classes: { public class Canvas

extends JPanel

{ ... public void

paintComponent (Graphics g) super.paintComponent

(g); ...

} ... 12-16

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 object’s 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.

12-17

Polymorphism (cont’d)

{ public void paintComponent (Graphics g) super.paintComponent(g); } } { for (Balloon b : balloons)

b.draw

(g, true); The correct

draw

method is called automatically for any specific type of balloon 12-18

Interfaces

Chess Checkers Chomp Player ComputerPlayer HumanPlayer Interface 12-19

Interfaces (cont’d)

• 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 Strategy Location findBestMove (ChompGame game); Location findRandomMove (ChompGame game); • “public abstract” is not written because all the methods are

public abstract

.

12-20

Interfaces (cont’d)

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

...

public String getName( )

{ return "Waltz"; }

public String getSteps (int m)

{ ... }

public int[ ] getBeat ( )

{ ... } } ...

12-21

Interfaces (cont’d)

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

12-22

Interfaces (cont’d)

} { public

interface Edible

String getFoodGroup(); int getCaloriesPerServing(); } { public class

Pancake implements Edible

...

} { public class Breakfast private int myTotalCalories = 0; ...

Polymorphism: the correct method is called for any specific { public void eat (

Edible

obj, int servings) myTotalCalories += obj.

getCaloriesPerServing

() * servings; type of

Edible (

e.g., a

Pancake)

} ...

12-23

Classes Interfaces

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

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

• An abstract class cannot be instantiated.

• An interface cannot be instantiated.

12-24

Classes Interfaces

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

• A concrete class that implements an interface must define all the methods specified by the interface. • A class can extend another class. A subclass can add methods and override some of its superclass’s methods.

• An interface can extend another interface (called its

superinterface

) by adding declarations of abstract methods.

12-25

Classes Interfaces

Differences • A class can extend only one class. • A class can have fields.

• A class defines its own constructors (or gets a default constructor). • A class can implement any number of interfaces. • An interface cannot have fields (except, possibly, some public static final constants).

• An interface has no constructors. 12-26

Classes Interfaces

Differences • A concrete class has all its methods defined. An abstract class usually has one or more abstract methods.

• All methods declared in an interface are abstract. • 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 very common. 12-27

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 superclass’s constructor called?

12-28

Review (cont’d)

• • • 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)

; ?

12-29

Review (cont’d)

• • 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?

12-30