Chapter 8 Inheritance.

Slides:



Advertisements
Similar presentations
Interfaces A Java interface is a collection
Advertisements

Chapter 8 Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
CS 211 Inheritance AAA.
Chapter 8 Inheritance 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter Day 21. © 2007 Pearson Addison-Wesley. All rights reserved7-2 Agenda Day 20 Problem set 4 Posted  10 problems from chapters 7 & 8  Due Nov 21.
Interfaces A Java interface is a collection of constants and abstract methods with a name that looks like a class name, i.e. first letter is capitalized.
Chapter 8 Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Chapter 10: Inheritance 1. Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called.
© 2004 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 : Inheritance Intermediate Java Programming Summer 2007.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
COS 312 DAY 13 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress Over due – Next progress report is March 26 Assignment 4 Posted – Chap 6 & 7 – Due.
Outline Creating Subclasses Overriding Methods Class Hierarchies Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright ©
Chapter 8 Inheritance Part 1. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Inheritance Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Chapter 8 Specialization aka Inheritance. 2 Inheritance  Review of class relationships  Uses – One class uses the services of another class, either.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
1 Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called the parent class, or.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
Object Oriented Concepts Recap OOP. The four Pillars of OOP Abstraction Encapsulation Inheritance Polymorphism.
Coming up: Inheritance
© 2004 Pearson Addison-Wesley. All rights reserved April 14, 2006 Polymorphism ComS 207: Programming I (in Java) Iowa State University, SPRING 2006 Instructor:
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Chapter 8 Inheritance 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
© 2004 Pearson Addison-Wesley. All rights reserved November 12, 2007 Inheritance ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
© 2004 Pearson Addison-Wesley. All rights reserved April 10, 2006 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Chapter 8 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
© 2004 Pearson Addison-Wesley. All rights reserved November 14, 2007 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL.
2/23- Interfaces Reference: Java 6.5 and 9.3. PA-4 Review Requirements PA3 – Grading Key PA4 Requirements Doc.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Chapter 5: Enhancing Classes
Polymorphism November 27, 2006 ComS 207: Programming I (in Java)
Lecture 12 Inheritance.
Chapter 8 Inheritance.
Inheritance and Polymorphism
03/10/14 Inheritance-2.
03/10/14 Chapter 9 Inheritance.
Inheritance November 10, 2006 ComS 207: Programming I (in Java)
Inheritance April 7, 2006 ComS 207: Programming I (in Java)
The super Reference Constructors cannot be used in child classes, even though they have public visibility Yet we often want to use the parent's constructor.
Advanced Programming Behnam Hatami Fall 2017.
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Overriding Methods & Class Hierarchies
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
Chapter 8 Inheritance Part 2.
Object-Oriented Design Part 2
Presentation transcript:

Chapter 8 Inheritance

Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined by the parent class © 2004 Pearson Addison-Wesley. All rights reserved

Inheritance Inheritance relationships are shown in a UML class diagram using a solid arrow with an unfilled triangular arrowhead pointing to the parent class Vehicle Car Proper inheritance creates an is-a relationship, meaning the child is a more specific version of the parent © 2004 Pearson Addison-Wesley. All rights reserved

Inheritance A programmer can tailor a derived class as needed by adding new variables or methods, or by modifying the inherited ones Software reuse is a fundamental benefit of inheritance By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software © 2004 Pearson Addison-Wesley. All rights reserved

Deriving Subclasses In Java, we use the reserved word extends to establish an inheritance relationship class Car extends Vehicle { // class contents } See Words.java (Chapter 9.1, page 472) See Book.java (Chapter 9.1, page 473) See Dictionary.java (Chapter 9.1, page 474) © 2004 Pearson Addison-Wesley. All rights reserved

The protected Modifier Visibility modifiers affect the way that class members can be used in a child class Variables and methods declared with private visibility cannot be referenced by name in a child class They can be referenced in the child class if they are declared with public visibility -- but public variables violate the principle of encapsulation There is a third visibility modifier that helps in inheritance situations: protected © 2004 Pearson Addison-Wesley. All rights reserved

The protected Modifier The protected modifier allows a child class to reference a variable or method directly in the child class It provides more encapsulation than public visibility, but is not as tightly encapsulated as private visibility A protected variable is visible to any class in the same package as the parent class The details of all Java modifiers are discussed in Appendix E Protected variables and methods can be shown with a # symbol preceding them in UML diagrams © 2004 Pearson Addison-Wesley. All rights reserved

Class Diagram for Words Book # pages : int + pageMessage() : void Dictionary - definitions : int + definitionMessage() : void Words + main (args : String[]) : void © 2004 Pearson Addison-Wesley. All rights reserved

The super Reference Constructors are not inherited, even though they have public visibility Yet we often want to use the parent's constructor to set up the "parent's part" of the object The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor See Words2.java (Chapter 9.1, page 476) See Book2.java (Chapter 9.1, page 477) See Dictionary2.java (Chapter 9.1, page 478) © 2004 Pearson Addison-Wesley. All rights reserved

The super Reference A child’s constructor is responsible for calling the parent’s constructor The first line of a child’s constructor should use the super reference to call the parent’s constructor The super reference can also be used to reference other variables and methods defined in the parent’s class © 2004 Pearson Addison-Wesley. All rights reserved

Inheritance Example © 2004 Pearson Addison-Wesley. All rights reserved

Inheritance Hierarchy © 2004 Pearson Addison-Wesley. All rights reserved

Multiple Inheritance Java supports single inheritance, meaning that a derived class can have only one parent class Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents Collisions, such as the same variable name in two parents, have to be resolved Java does not support multiple inheritance In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead © 2004 Pearson Addison-Wesley. All rights reserved

Overriding Methods A child class can override the definition of an inherited method in favor of its own The new method must have the same signature as the parent's method, but can have a different body The type of the object executing the method determines which version of the method is invoked See Messages.java (Chapter 9.2, page 481) See Thought.java (Chapter 9.2, page 482) See Advice.java (Chapter 9.2, page 483) © 2004 Pearson Addison-Wesley. All rights reserved

Overriding A method in the parent class can be invoked explicitly using the super reference If a method is declared with the final modifier, it cannot be overridden The concept of overriding can be applied to data and is called shadowing variables Shadowing variables should be avoided because it tends to cause unnecessarily confusing code © 2004 Pearson Addison-Wesley. All rights reserved

Overloading vs. Overriding Overloading deals with multiple methods with the same name in the same class, but with different signatures Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overloading lets you define a similar operation in different ways for different parameters Overriding lets you define a similar operation in different ways for different object types © 2004 Pearson Addison-Wesley. All rights reserved

Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy Business KMart Macys ServiceBusiness Kinkos RetailBusiness © 2004 Pearson Addison-Wesley. All rights reserved

Class Hierarchies Two children of the same parent are called siblings Common features should be put as high in the hierarchy as is reasonable An inherited member is passed continually down the line Therefore, a child class inherits from all its ancestor classes There is no single class hierarchy that is appropriate for all situations © 2004 Pearson Addison-Wesley. All rights reserved

© 2004 Pearson Addison-Wesley. All rights reserved

The Object Class A class called Object is defined in the java.lang package of the Java standard class library All classes are derived from the Object class If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class Therefore, the Object class is the ultimate root of all class hierarchies © 2004 Pearson Addison-Wesley. All rights reserved

The Object Class The Object class contains a few useful methods, which are inherited by all classes For example, the toString method is defined in the Object class Every time we define the toString method, we are actually overriding an inherited definition The toString method in the Object class is defined to return a string that contains the name of the object’s class along with some other information © 2004 Pearson Addison-Wesley. All rights reserved

The Object Class The equals method of the Object class returns true if two references are aliases We can override equals in any class to define equality in some more appropriate way As we've seen, the String class defines the equals method to return true if two String objects contain the same characters The designers of the String class have overridden the equals method inherited from Object in favor of a more useful version © 2004 Pearson Addison-Wesley. All rights reserved

Visibility Revisited It's important to understand one subtle issue related to inheritance and visibility All variables and methods of a parent class, even private members, are inherited by its children As we've mentioned, private members cannot be referenced by name in the child class However, private members inherited by child classes exist and can be referenced indirectly © 2004 Pearson Addison-Wesley. All rights reserved

Visibility Revisited Because the parent can refer to the private member, the child can reference it indirectly using its parent's methods The super reference can be used to refer to the parent class, even if no object of the parent exists See FoodAnalyzer.java (Chapter 9.4, page 490) See FoodItem.java (Chapter 9.4, page 491) See Pizza.java (Chapter 9.4, page 492) © 2004 Pearson Addison-Wesley. All rights reserved

Constructors in Inheritance Do you have to provide a constructor for a class? No, a no-argument, default constructor is implicitly provided This default constructor calls the no-argument constructor of the super-class If super-class does not have no-argument version of the constructor A compilation error occurs Make sure there is such a constructor in the superclass What if there is no super-class? Object class is the implicit super-class, and it does have a no-argument constructor

Constructors What happens when no constructor is defined for a class?  No-argument constructor will be provided implicitly for that class class C2 extends C1 { // no constructor is defined public C2() { // this constructor is super(); // automatically provided by Java. } If another constructor of the class is present, no-argument version of the constructor will not be provided automatically. CS102 Algorithims and Programming II

Constructors of Sub-Classes The initialization of the fields of a sub-class consists of two phases: The initialization of the inherited fields The initialization of the fields that are declared in that sub-class. One of the constructors of the super-class must be invoked to initialize the fields inherited from the super-class. A super-class constructor must be invoked explicitly; Otherwise the no-argument constructor of the super-class will be automatically invoked This invocation must be the first statement of the constructor of the sub-class. (Or the one of the constructors of the sub-class must invoke another version of the constructor of that sub-class). CS102 Algorithims and Programming II

Constructors of Sub-Classes class C1 { private int x; public C1() { x=0; } public C1(int xv) { x=xv; } } class C2 extends C1 { private int y; public C2(int xv, int yv) { super(xv); the constructor of the super-class is explicitly invoked y = yv; public C2(int yv) { this(1,yv); Another version of the constructor of this class is invoked public C2() { y = 2; No-argument version of the constructor of the super-class } } is implicitly invoked. super(); CS102 Algorithims and Programming II

Order of Initialization Step The fields of the super-class are initialized using default values. One of the constructors of the super-class is executed. The fields of the extended class (sub-class) are initialized using the default values. One of the constructors of the extended class (sub-class) is executed. CS102 Algorithims and Programming II

Order of Initialization Step (cont.) class C1 { private int x = 1; // executed first public C1() { x = 2; // executed second } class C2 extends C1 { private int y = 3; // executed third public C2() { super(); y = 4 ; // executed fourth CS102 Algorithims and Programming II

Abstract Classes An abstract class in a class hierarchy represents a generic concept Common elements in a hierarchy that are too generic to instantiate Cannot be instantiated abstract on the class header: public abstract class Product { // contents } © 2004 Pearson Addison-Wesley. All rights reserved

Abstract Classes abstract classes typically have: abstract methods with no definitions (like an interface) probably also non-abstract methods with full definitions Does not have to contain abstract methods -- simply declaring it as abstract makes it so The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract © 2004 Pearson Addison-Wesley. All rights reserved

Abstract Classes abstract class A1 { abstract void m1(); abstract String m2(); } class C1 extends A1 { void m1() { System.out.println(“C1-m1”); } String m2() { return “C1-m2”; } abstract C2 extends A1 { void m1() { System.out.println(“C2-m1”); }  C2 must be abstract, because it does not implement the abstract method m2. CS102 Algorithims and Programming II

Abstract Classes Abstract methods cannot be defined as final or static final cannot be overridden (contradiction!) static could be invoked by just using the name of the class – can’t invoke it with no implementation © 2004 Pearson Addison-Wesley. All rights reserved

Interfaces A Java interface is a collection of abstract methods and constants An abstract method is a method header without a method body abstract - but because all methods in an interface are abstract, usually it is left off An interface establishes a set of methods that a class will implement Similar to abstract class but all methods are abstract (and all properties are constant) © 2004 Pearson Addison-Wesley. All rights reserved

Interfaces interface I1 { Although we do not write here, it is assumed that CONST1 is declared as a constant (with int CONST1=5; keywords public, final and static) void m1(); Although we do not write here, it is assumed } that m1 is declared with keywords public and abstract. Interface methods are public by default CS102 Algorithims and Programming II

Interfaces interface is a reserved word None of the methods in an interface are given a definition (body) public interface Doable { public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } A semicolon immediately follows each method header © 2004 Pearson Addison-Wesley. All rights reserved

Interfaces Defines similarities that multiple classes share to tie elements of several classes together - without having an inheritance relationship, so still no multiple inheritance separate design from coding An interface cannot be instantiated A class implements an interface by: stating so in the class header Implementing all abstract methods in the interface, plus maybe some others © 2004 Pearson Addison-Wesley. All rights reserved

Interfaces public class CanDo implements Doable { public void doThis () // whatever } public void doThat () // etc. implements is a reserved word Each method listed in Doable is given a definition © 2004 Pearson Addison-Wesley. All rights reserved

Implementing Interfaces (cont.) An interface can be implemented by multiple classes. Each implementing class can provide their own unique versions of the method definitions. interface I1 { void m1() ; } class C1 implements I1 { public void m1() { System.out.println(“Implementation in C1”); } class C2 implements I1 { public void m1() { System.out.println(“Implementation in C2”); } CS102 Algorithims and Programming II

© 2004 Pearson Addison-Wesley. All rights reserved

Interfaces A class can implement multiple interfaces The interfaces are listed in the implements clause The class must implement all methods in all interfaces listed in the header class ManyThings implements interface1, interface2 { // all methods of both interfaces } © 2004 Pearson Addison-Wesley. All rights reserved

Implementing More Than One Interface interface I1 { void m1(); } interface I2 { void m2() ; C must implement all methods in I1 and I2. void m3() ; class C implements I1, I2 { public void m1() { System.out.println(“C-m1”); } public void m2() { System.out.println(“C-m2”); } public void m3() { System.out.println(“C-m3”); } CS102 Algorithims and Programming II

Resolving Name Conflicts Among Interfaces Since a class may implement more than one interface, the names in those interfaces may collide. To solve name collisions, Java use a simple mechanism. Two methods that have the same name will be treated as follows in Java: If they are different signature, they are considered to be overloaded. If they have the same signature and the same return type, they are considered to be the same method and they collapse into one. If they have the same signature and the different return types, a compilation error will occur. CS102 Algorithims and Programming II

Resolving Name Conflicts Among Interfaces interface I1 { void m1(); void m2(); void m3(); } interface I2 { void m1(int a); There will be a compilation error for m3. int m3(); class C implements I1, I2 { public void m1() { … } // implementation of m1 in I1 public void m1(int x) { … } // implementation of m1 in I2 public void m2() { … } // implementation of m2 in I1 and I2 CS102 Algorithims and Programming II

Inheritance Relation Among Interfaces Same as classes, interfaces can hold inheritance relation among them interface I2 extends I1 { … } Now, I2 contains all abstract methods of I1 plus its own abstract methods. The classes implementing I2 must implement all methods in I1 and I2. CS102 Algorithims and Programming II

Interfaces as Data Types Interfaces (same as classes) can be used as data types. Different from classes: We cannot create an instance of an interface. interface I1 { … } class C1 implements I1 { … } class C2 extends C1 { … } // a variable can be declared as type I1 I1 x; A variable declared as I1, can store objects of C1 and C2. More later… CS102 Algorithims and Programming II

Interfaces The Java standard class library contains many helpful interfaces The Comparable interface contains one abstract method called compareTo, which is used to compare two objects We discussed the compareTo method of the String class in Chapter 5 The String class implements Comparable, giving us the ability to put strings in lexicographic order © 2004 Pearson Addison-Wesley. All rights reserved

The Comparable Interface Any class can implement Comparable to provide a mechanism for comparing objects of that type if (obj1.compareTo(obj2) < 0) System.out.println ("obj1 is less than obj2"); The value returned from compareTo should be negative if obj1 is less that obj2, 0 if they are equal, and positive if obj1 is greater than obj2 When a programmer designs a class that implements the Comparable interface, it should follow this intent © 2004 Pearson Addison-Wesley. All rights reserved

The Comparable Interface It's up to the programmer to determine what makes one object less than another For example, you may define the compareTo method of an Employee class to order employees by name (alphabetically) or by employee number The implementation of the method can be as straightforward or as complex as needed for the situation © 2004 Pearson Addison-Wesley. All rights reserved

The Iterator Interface As we discussed in Chapter 5, an iterator is an object that provides a means of processing a collection of objects one at a time An iterator is created formally by implementing the Iterator interface, which contains three methods The hasNext method returns a boolean result – true if there are items left to process The next method returns the next object in the iteration The remove method removes the object most recently returned by the next method © 2004 Pearson Addison-Wesley. All rights reserved

The Iterator Interface By implementing the Iterator interface, a class formally establishes that objects of that type are iterators The programmer must decide how best to implement the iterator functions Once established, the for-each version of the for loop can be used to process the items in the iterator © 2004 Pearson Addison-Wesley. All rights reserved

Interfaces You could write a class that implements certain methods (such as compareTo) without formally implementing the interface (Comparable) However, formally establishing the relationship between a class and an interface allows Java to deal with an object in certain ways Interfaces are a key aspect of object-oriented design in Java We discuss this idea further in Chapter 9 © 2004 Pearson Addison-Wesley. All rights reserved

When to use Abstract Methods & Abstract Class? Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations These subclasses extend the same Abstract class and provide different implementations for the abstract methods Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class. © 2004 Pearson Addison-Wesley. All rights reserved

Why do we use Interfaces? Reason #1 To reveal an object's programming interface (functionality of the object) without revealing its implementation This is the concept of encapsulation The implementation can change without affecting the caller of the interface The caller does not need the implementation at the compile time It needs only the interface at the compile time During runtime, actual object instance is associated with the interface type © 2004 Pearson Addison-Wesley. All rights reserved

Why do we use Interfaces? Reason #2 To have unrelated classes implement similar methods (behaviors) One class is not a sub-class of another Example: Class Line and class MyInteger They are not related through inheritance You want both to implement comparison methods checkIsGreater(Object x, Object y) checkIsLess(Object x, Object y) checkIsEqual(Object x, Object y) Define Comparison interface which has the three abstract methods above © 2004 Pearson Addison-Wesley. All rights reserved

Why do we use Interfaces? Reason #3 To model multiple inheritance A class can implement multiple interfaces while it can extend only one class © 2004 Pearson Addison-Wesley. All rights reserved

Interface vs. Abstract Class All methods of an Interface are abstract methods while some methods of an Abstract class are abstract methods Abstract methods of abstract class have abstract modifier An interface can only define constants while abstract class can have fields Interfaces have no direct inherited relationship with any particular class, they are defined independently Interfaces themselves have inheritance relationship among themselves © 2004 Pearson Addison-Wesley. All rights reserved

Problem of Rewriting an Existing Interface Consider an interface that you have developed called DoIt: public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); } Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes: boolean didItWork(int i, double x, String s); If you make this change, all classes that implement the old DoIt interface will break because they don't implement all methods of the interface anymore © 2004 Pearson Addison-Wesley. All rights reserved

Solution of Rewriting an Existing Interface Create more interfaces later For example, you could create a DoItPlus interface that extends DoIt: public interface DoItPlus extends DoIt { boolean didItWork(int i, double x, String s); } Now users of your code can choose to continue to use the old interface or to upgrade to the new interface © 2004 Pearson Addison-Wesley. All rights reserved

When to use an Abstract Class over Interface? For non-abstract methods, you want to use them when you want to provide common implementation code for all sub-classes Reducing the duplication For abstract methods, the motivation is the same with the ones in the interface – to impose a common behavior for all sub-classes without dictating how to implement it Remember a concrete can extend only one super class whether that super class is in the form of concrete class or abstract class © 2004 Pearson Addison-Wesley. All rights reserved

Summary Chapter 8 focused on: deriving new classes from existing classes the protected modifier creating class hierarchies abstract classes indirect visibility of inherited members designing for inheritance © 2004 Pearson Addison-Wesley. All rights reserved