Ch11

1,110
-1

Published on

Hariprasanna V (9843824677)

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,110
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
43
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Class hierarchies is the heart of OOP.
  • Also finish the Dance Studio project, started in Chapter 3.
  • A subclass inherits all the fields and methods of its superclass, but not constructors.
  • The class Biped is a generic class that represents any kind of “creature” that moves on two legs. (The term biped comes from Latin: bi means “two,” and ped means “foot.”)
  • If two classes share a lot of code, it makes sense to define a common superclass and factor out common code into it.
  • So inheritance helps to eliminate duplicating code in two ways: (1) by factoring out common code and (2) by writing more general methods.
  • Java implements polymorphism through a technique known as late (or dynamic ) method binding : which method to call is defined at run time, not compile time. Each object holds a table of entry points to its methods, so each object itself knows exactly what to do when one of its methods is called.
  • We pass to a method a specific type of object. Inside the method the object is disguised as a more generic type, but “deep inside” it still “knows” what type of object it is.
  • An abstract class can have fields, constructors, and regular methods.
  • Additional error checking: if a concrete (non-abstract) class extends an abstract class, it must override all of the abstract methods.
  • JComponent starts the new Swing hierarchy added in Java 2.
  • Superclass’s constructors are called using the keyword super , as discussed shortly.
  • Object ’s toString returns a string that holds object’s class name and hex address in memory -- not very useful for most classes. For example, if we comment out for a moment the toString method in Fraction and execute System.out.println(new Fraction(2, 3)); we will see something like [email_address] We need to override Object ’s toString in our class if we want to convert our objects to strings in a meaningful way.
  • In this example super passes “up” all the parameters received by Walker ’s constructor. In general, this does not have to be the case.
  • This error message pops up unexpectedly and appears quite puzzling.
  • Superclass’s constructor is called to initialize superclass’s fields.
  • Here nextStep calls superclass’s nextStep , the same method that it overrides. This is common, but, in general, a method can explicitly call any method of the superclass. For example, nextStep could call super.stop() .
  • Subclasses of library classes also often call superclass’s constructors. For example: public class Hello extends JFrame { public Hello() { super("Hello, World"); // sets the title bar // text ... } }
  • In the computer world, the term interface refers to any mechanism that connects two devices or entities and defines the rules for their interaction.
  • An interface can also have public static constants.
  • It is not sufficient to supply all the methods -- we must state “implements” in the class’s header. An abstract class can supply some of the interface’s methods, leaving others abstract.
  • The main advantage of interfaces over abstract classes is that a class can implement several interfaces but extend only one superclass.
  • Obviously an interface cannot help to factor out common code from several classes (because an interface does not have any executable code); but an interface can help to eliminate duplicate code by letting us write more general methods.
  • A class in a hierarchy accumulates all the secondary data types of its ancestors, including all the interfaces that they implement.
  • If a concrete class implements several interfaces, it must supply all of their methods.
  • Interfaces is Java’s response to “multiple inheritance.”
  • Strategically positioned interfaces in this application add flexibility. For example, in Chapter 3 we were able to easily turn Dance Studio into First Steps by replacing a DanceGroup and Dancer s with a WalkingGroup and Walker s (or a PacingGroup and Pacer s).
  • Describe two ways for eliminating duplicate code using class hierarchies. Factoring out common code and writing more general methods that take more generic parameters. What is an abstract class? A class that has one or several abstract methods and is declared abstract. Why is it better to use an abstract method rather than an empty method? The compiler makes sure that a concrete class overrides an abstract method, so you can’t accidentally forget to override it. Define concrete class. A class that is not abstract: all methods are defined. What happens when a constructor of a subclass does not have a super statement? Is superclass’s constructor called? Yes. Superclass’s no-args constructor is called, and it must exist then (either defined explicitly or provided by default, when no constructors are explicitly defined).
  • Can an abstract class be instantiated? No. Can someMethod1 have a call super.someMethod2() ? Yes. What happens if, by mistake, a programmer puts in his paintComponent method a call paintComponent(g); instead of super.paintComponent(g); ? Infinite recursion, which blows the stack.
  • What is the main difference between an abstract class and an interface? An abstract class can have fields, constructors, and regular methods; an interface does not have any executable code. Can a class implement several interfaces? Yes, that’s the whole point. Suppose you declare a variable of an interface type. What type of value can be assigned to that variable? An object of any class that implements the interface. What is the main advantage of interfaces over abstract classes? A class can implement several interfaces.
  • Ch11

    1. 1. Class Hierarchies and Interfaces Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved .
    2. 2. Objectives: <ul><li>Understand class hierarchies and polymorphism </li></ul><ul><li>Learn about abstract classes </li></ul><ul><li>Learn the syntax for calling superclass’s constructors and methods </li></ul><ul><li>Understand interfaces </li></ul>
    3. 3. Inheritance <ul><li>Inheritance represents the IS-A relationship between objects: an object of a subclass IS-A(n) object of the superclass. </li></ul>Superclass (Base class) Subclass (Derived class) Subclass extends Superclass
    4. 4. Class Hierarchies <ul><li>Using inheritance, a programmer can define a hierarchy of classes. </li></ul>Biped Walker Hopper Dancer ToedInWalker CharlieChaplin
    5. 5. Class Hierarchies (cont’d) <ul><li>Help reduce duplication of code by factoring out common code from similar classes into a common superclass. </li></ul>Biped Constructor Accessors turnLeft turnRight turnAround draw Walker Constructor firstStep nextStep stop distanceTraveled Hopper Constructor firstStep nextStep stop distanceTraveled
    6. 6. Class Hierarchies (cont’d) <ul><li>Help reduce duplication of code by letting you write more general methods in client classes. </li></ul>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 Hopper due to polymorphism
    7. 7. Polymorphism <ul><li>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. </li></ul><ul><li>Once you define a common superclass, polymorphism is just there  no need to do anything special. </li></ul>
    8. 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.
    9. 9. Abstract Classes <ul><li>Some of the methods in a class can be declared abstract and left with only signatures defined </li></ul><ul><li>A class with one or more abstract methods must be declared abstract </li></ul>public abstract class Biped { ... public abstract void firstStep(); public abstract void nextStep(); public abstract void stop(); ... public void draw(Graphics g) { ... } } Abstract methods
    10. 10. Abstract Classes (cont’d) <ul><li>Abstract classes serve as common superclasses for more specific classes </li></ul><ul><li>An abstract method provides an opportunity for the compiler to do additional error checking </li></ul><ul><li>Abstract classes and methods are needed for polymorphism to work </li></ul><ul><li>Abstract classes are closer to the root of the hierarchy; they describe more abstract objects </li></ul>
    11. 11. Abstract Classes (cont’d) A fragment of Java library GUI class hierarchy (abstract classes are boxed)
    12. 12. Abstract Classes (cont’d) <ul><li>Java does not allow us to instantiate (that is, create objects of) abstract classes </li></ul><ul><li>Still, an abstract class can have constructors  they can be called from constructors of subclasses </li></ul><ul><li>A class with no abstract methods is called concrete </li></ul>
    13. 13. Class Object <ul><li>In Java every class by default extends a library class Object (from java.lang ) </li></ul><ul><li>Object is a concrete class </li></ul>public class Object { public String toString {...} public boolean equals (Object other) {... } public int hashCode() { ... } // a few other methods ... } Methods redefined (overridden) as necessary
    14. 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.
    15. 15. Calling Superclass’s Constructors (cont’d) <ul><li>One of the superclass’s constructors is always called, but you don’t have to have an explicit super statement. </li></ul><ul><li>If there is no explicit call to super , then superclass’s no-args constructor is called by default. </li></ul>Must be defined then. If not defined  syntax error: cannot find symbol : constructor ...
    16. 16. Calling Superclass’s Constructors (cont’d) <ul><li>Superclass’s constructor calls its superclass’s constructor, and so on, all the way up to Object ’s constructor. </li></ul>Biped Walker Object super( ) super(...)
    17. 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.
    18. 18. Calling Superclass’s Methods (cont’d) <ul><li>super. calls are often used in subclasses of library classes: </li></ul>public class Canvas extends JPanel { ... public void paintComponent (Graphics g) { super.paintComponent (g); ... } ...
    19. 19. Interfaces DanceFloor DanceGroup ControlPanel Band Dancer Aerobics Waltz Rumba Cha-Cha-Cha Salsa Dance Interface
    20. 20. Interfaces (cont’d) <ul><li>An interface in Java is like an abstract class, but it does not have any fields or constructors, and all its methods are abstract. </li></ul><ul><li>“public abstract” is not written because all the methods are public abstract . </li></ul>public interface Dance { DanceStep getStep (int i); int getTempo (); int getBeat (int i); }
    21. 21. Interfaces (cont’d) <ul><li>We must “officially” state that a class implements an interface. </li></ul><ul><li>A concrete class that implements an interface must supply all the methods of that interface. </li></ul>public class Waltz implements Dance { ... // Methods: public DanceStep getStep (int i) { ... } public int getTempo () { return 750; } public int getBeat (int i) { ... } ... }
    22. 22. Interfaces (cont’d) <ul><li>A class can implement several interfaces. </li></ul><ul><li>Like an abstract class, an interface supplies a secondary data type to objects of a class that implements that interface. </li></ul><ul><li>You can declare variables and parameters of an interface type. </li></ul><ul><li>Polymorphism fully applies to objects disguised as interface types. </li></ul>Dance d = new Waltz( );
    23. 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 { ... }
    24. 24. Classes Interfaces <ul><li>A superclass provides a secondary data type to objects of its subclasses. </li></ul><ul><li>An abstract class cannot be instantiated. </li></ul><ul><li>An interface provides a secondary data type to objects of classes that implement that interface. </li></ul><ul><li>An interface cannot be instantiated. </li></ul>Similarities
    25. 25. Classes Interfaces <ul><li>A concrete subclass of an abstract class must define all the inherited abstract methods. </li></ul><ul><li>A class can extend another class. A subclass can add methods and override some of its superclass’s methods. </li></ul><ul><li>A concrete class that implements an interface must define all the methods specified by the interface. </li></ul><ul><li>An interface can extend another interface (called its superinterface ) by adding declarations of abstract methods. </li></ul>Similarities
    26. 26. Classes Interfaces <ul><li>A class can extend only one class. </li></ul><ul><li>A class can have fields. </li></ul><ul><li>A class defines its own constructors (or gets a default constructor). </li></ul><ul><li>A class can implement any number of interfaces. </li></ul><ul><li>An interface cannot have fields (except, possibly, some public static final constants). </li></ul><ul><li>An interface has no constructors. </li></ul>Differences
    27. 27. Classes Interfaces <ul><li>A concrete class has all its methods defined. An abstract class usually has one or more abstract methods. </li></ul><ul><li>Every class is a part of a hierarchy of classes with Object at the top. </li></ul><ul><li>All methods declared in an interface are abstract. </li></ul><ul><li>An interface may belong to a small hierarchy of interfaces, but this is not as common. </li></ul>Differences
    28. 28. Dance Studio
    29. 29. Review <ul><li>Describe two ways for eliminating duplicate code using class hierarchies. </li></ul><ul><li>What is an abstract class? </li></ul><ul><li>Why is it better to use an abstract method rather than an empty method? </li></ul><ul><li>Define concrete class. </li></ul><ul><li>What happens when a constructor of a subclass does not have a super statement? Is superclass’s constructor called? </li></ul>
    30. 30. Review (cont’d) <ul><li>Can an abstract class be instantiated? </li></ul><ul><li>Can someMethod1 have a call super.someMethod2 ( ) ? </li></ul><ul><li>What happens if, by mistake, a programmer puts in his paintComponent method a call paintComponent(g); </li></ul><ul><li>instead of </li></ul><ul><li>super.paintComponent(g); </li></ul><ul><li>? </li></ul>
    31. 31. Review (cont’d) <ul><li>What is the main difference between an abstract class and an interface? </li></ul><ul><li>Can a class implement several interfaces? </li></ul><ul><li>Suppose you declare a variable of an interface type. What type of value can be assigned to that variable? </li></ul><ul><li>What is the main advantage of interfaces over abstract classes? </li></ul>

    ×