This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Class Hierarchies (cont’d)• 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(); 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 either Walker or Hopperdue to polymorphism
11-7
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.
11-8
Polymorphism (cont’d)
public void moveAcross (Biped creature, int distance) { creature.firstStep(); while (creature.distanceTraveled () < distance) creature.nextStep(); creature.stop(); }
The actual parameter passed to this method can be a Walker, a Hopper, etc. any subclass of Biped.
Correct methods will be called automatically for any specific type of creature: Walker’s methods for Walker, Hopper’s for Hopper, etc.
11-9
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-10
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 and methods are needed for polymorphism to work
• Abstract classes are closer to the root of the hierarchy; they describe more abstract objects
A fragment of Java library GUI class hierarchy (abstract classes are boxed)
11-12
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
11-13
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-14
Calling Superclass’s Constructors
public class Walker extends Biped{ // Constructor public Walker(int x, int y, Image leftPic, Image rightPic) { super(x, y, leftPic, rightPic); ... }}
Biped
Walker
Calls Biped’s constructor
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.
11-15
Calling 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 ...
11-16
Calling Superclass’s Constructors (cont’d)• Superclass’s constructor calls its superclass’s
constructor, and so on, all the way up to Object’s constructor.
Biped
Walker
Objectsuper( )
super(...)
11-17
Calling Superclass’s Methods
public class CharlieChaplin extends Walker{ ... public void nextStep () { turnFeetIn(); super.nextStep(); turnFeetOut(); } ...}
Walker
CharlieChaplin
Calls Walker’s nextStep
super.someMethod refers to someMethod in the nearest class, up the inheritance line, where someMethod is defined.
11-18
Calling Superclass’s Methods (cont’d)• super. calls are often used in subclasses
of library classes:
public class Canvas extends JPanel{ ... public void paintComponent (Graphics g) { super.paintComponent (g); ... } ...
11-19
Interfaces
DanceFloor
DanceGroup
ControlPanel
Band
Dancer
Aerobics
Waltz
Rumba
Cha-Cha-Cha
Salsa
Dance
Interface
11-20
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 abstract” is not written because all the methods are public abstract.
public interface Dance{ DanceStep getStep (int i); int getTempo (); int getBeat (int i);}
11-21
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{ ... // Methods: public DanceStep getStep (int i) { ... } public int getTempo () { return 750; } public int getBeat (int i) { ... } ...}
11-22
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.
• Polymorphism fully applies to objects disguised as interface types.
Dance d = new Waltz( );
11-23
Interfaces (cont’d)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 correct method is called for any specific type of Edible, e.g., a Pancake
public class Pancake implements Edible{ ...}
11-24
Classes Interfaces
• A superclass provides a secondary data type to objects of its subclasses.
• An abstract class cannot be instantiated.
• An interface provides a secondary data type to objects of classes that implement that interface.
• An interface cannot be instantiated.
Similarities
11-25
Classes Interfaces
• 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 superclass’s methods.
• A concrete class that implements an interface must define all the methods specified by the interface.
• An interface can extend another interface (called its superinterface) by adding declarations of abstract methods.
Similarities
11-26
Classes Interfaces
• 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.
Differences
11-27
Classes Interfaces
• 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.
• All methods declared in an interface are abstract.
• An interface may belong to a small hierarchy of interfaces, but this is not as common.
Differences
11-28
DanceStudio
DanceStudio
DanceFloor
DanceGroup
ControlPanel
«interface» Dance Dancer Biped
Foot
CoordinateSystem
DanceStep
A B
extends
depends on
has
implements
Band
DanceLesson
«interface» StudentGroup
< various dances >
AbstractDance
11-29
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?
11-30
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);
?
11-31
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?