Java Methods ObjectOriented Programming and Data Structures 2
Java Methods Object-Oriented Programming and Data Structures 2 nd AP edition with Grid. World Maria Litvin ● Gary Litvin Class Hierarchies and Interfaces Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. 1
Objectives: • Understand class hierarchies and polymorphism • Learn about abstract classes • Learn the syntax for calling superclass’s constructors and methods • Understand interfaces 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. 3
Class Hierarchies • Using inheritance, a programmer can define a hierarchy of classes. 4
Class Hierarchies (cont’d) • Help reduce duplication of code by factoring out common code from similar classes into a common superclass. Bug Constructor can. Move move turn act (redefined) Actor Constructor Accessors put. Self. In. Grid remove. Self. From. Grid set. Color move. To act Flower Constructor act (redefined) 5
Class Hierarchies (cont’d) • Help reduce duplication of code by letting you write more general methods in client classes. public void add (Location loc, Bug occupant) { occupant. put. Self. In. Grid(get. Grid(), loc); } public void add (Location loc, Flower occupant) { occupant. put. Self. In. Grid(get. Grid(), loc); } Works for a Bug or a Flower any Actor public void add (Location loc, Actor occupant) { occupant. put. Self. In. Grid(get. Grid(), loc); } 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 public abstract class Actor {. . . public abstract void act(); } Abstract method 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 8
Abstract Classes (cont’d) A fragment of Java library GUI class hierarchy (abstract classes are boxed) 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 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 to. String {. . . } public boolean equals (Object other) {. . . } public int hash. Code() {. . . } Methods redefined (overridden) as necessary // a few other methods. . . } 11
Invoking Superclass’s Constructors Bug UTurn. Bug public class UTurn. Bug extends Bug { // Constructor public UTurn. Bug ( ) { Calls Bug’s super(Color. YELLOW); . . . constructor } } The number / types of parameters passed to super must match parameters of one of the If present, must be superclass’s constructors. the first statement 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. . . 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. super( ) Object Actor Flower 14
Calling Superclass’s Methods Flower Wilting. Flower public class Wilting. Flower extends Flower {. . . super. some. Method public void act() refers to some. Method in { the nearest class, up the age++; inheritance line, where if (age > life. Span) some. Method is defined. { remove. Self. From. Grid(); } else super. act(); Calls Flower’s act } } 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 paint. Component (Graphics g) { super. paint. Component (g); . . . }. . . 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. 17
Polymorphism (cont’d) public void step() {. . . for (Actor a : actors) { // only act if another actor hasn't removed a if (a. get. Grid() == gr) a. act(); The correct act method is } called automatically for any } specific type of actor. 18
Interfaces YMCA Dancing. Bug Dancing. Crab Dance Waltz Conga Maracas Interface 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 Dance { String get. Name (); String get. Steps (int m); int[] get. Beat (); } • “public abstract” is not written because all the methods are public abstract. 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 get. Name( ) { return "Waltz"; } public String get. Steps(int m) {. . . } public int[] get. Beat( ) {. . . } 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. 22
Interfaces (cont’d) public interface Edible { String get. Food. Group(); int get. Calories. Per. Serving(); } public class Pancake implements Edible {. . . } public class Breakfast Polymorphism: { the correct private int my. Total. Calories = 0; method is called. . . for any specific public void eat (Edible obj, int servings) type of Edible { (e. g. , a Pancake) my. Total. Calories += obj. get. Calories. Per. Serving () * servings; }. . . } 23
Classes Interfaces Similarities • 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. 24
Classes Interfaces Similarities • 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. 25
Classes Interfaces Differences • A class can extend only one class. • A class can have fields. • A class can implement any number of interfaces. • 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. 26
Classes Interfaces Differences • 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 very common. 27
Grid. World Dance 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 superclass’s constructor called? 29
Review (cont’d) • Can an abstract class be instantiated? • Can some. Method 1 have a call super. some. Method 2 ( )? • What happens if, by mistake, a programmer puts in his paint. Component method a call paint. Component(g); instead of super. paint. Component(g); ? 30
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? 31
- Slides: 31