More Inheritance Abstract Classes Interfaces Briana B. Morrison CSE 1302C Spring 2010.

Slides:



Advertisements
Similar presentations
Interfaces A Java interface is a collection
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/George Koutsogiannakis 1.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
1 Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L 9.1 – 9.3.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Abstract Classes.
1 Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
ECE122 L22: Polymorphism Using Inheritance April 26, 2007 ECE 122 Engineering Problem Solving with Java Lecture 22 Polymorphism using Inheritance.
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.
© 2004 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 : Inheritance Intermediate Java Programming Summer 2007.
Abstract Classes and Interfaces Lecture 2 – 9/6/2012.
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
© 2004 Pearson Addison-Wesley. All rights reserved April 17, 2006 Polymorphism (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
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.
1 Advanced Polymorphism Polymorphism Review Comparator Interface Sorting with Comparators Selection Sort Insertion Sort.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
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.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
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.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
Chapter 8 Inheritance 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Designing Classes Chapter 3. Contents Encapsulation Specifying Methods Java Interfaces – Writing an Interface – Implementing an Interface – An Interface.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
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.
1 Lecture 8 b Data Structures b Abstraction b The “Structures” package b Preconditions and postconditions b Interfaces b Polymorphism b Vector class b.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
CS 116 Object Oriented Programming II Lecture 9 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CS 116 Object Oriented Programming II Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
2/23- Interfaces Reference: Java 6.5 and 9.3. PA-4 Review Requirements PA3 – Grading Key PA4 Requirements Doc.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Chapter 5: Enhancing Classes
Polymorphism November 27, 2006 ComS 207: Programming I (in Java)
Chapter 9 Polymorphism.
03/10/14 Inheritance-2.
OBJECT ORIENTED PROGRAMMING II LECTURE 7 GEORGE KOUTSOGIANNAKIS
Polymorphism.
Designing for Inheritance
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
OBJECT ORIENTED PROGRAMMING II LECTURE 9 GEORGE KOUTSOGIANNAKIS
Overriding Methods & Class Hierarchies
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
Chapter 8 Inheritance.
Chapter 8 Inheritance Part 2.
Object-Oriented Design Part 2
Presentation transcript:

More Inheritance Abstract Classes Interfaces Briana B. Morrison CSE 1302C Spring 2010

2 CSE 1302C Topics Abstract classes (p217) Polymorph Hiding members Interfaces

3 CSE 1302C Polymorphism An important concept in inheritance is that an object of a subclass is also an object of any of its superclasses. That concept is the basis for an important OOP feature, called polymorphism. Polymorphism simplifies the processing of various objects in the same class hierarchy because we can use the same method call for any object in the hierarchy using a superclass object reference.

4 CSE 1302C Example Hierarchy Consider this hierarchy The superclass is Figure, which defines a method called doIt() One of two subclasses redefines doIt() If I have a variable v and say v.doIt() which method is called? doIt()

5 CSE 1302C Binding Consider the following method invocation: obj.doIt(); At some point, this invocation is bound to the definition of the method that it invokes If this binding occurred at compile time, then that line of code would call the same method every time However, C# defers method binding until run time for virtual methods-- this is called dynamic binding or late binding Late binding provides flexibility in program design

6 CSE 1302C Polymorphism The term polymorphism literally means "having many forms" A polymorphic reference is a variable that can refer to different types of objects at different points in time The method invoked through a polymorphic reference can change from one invocation to the next All object references in C# are potentially polymorphic

7 CSE 1302C Polymorphism Suppose we create the following reference variable: Occupation job; C# allows this reference to point to an Occupation object, or to any object of any compatible type This compatibility can be established using inheritance or using interfaces Careful use of polymorphic references can lead to elegant, robust software designs

8 CSE 1302C References and Inheritance Assigning a child object to a parent reference is considered to be a widening conversion, and can be performed by simple assignment Assigning an parent object to a child reference can be done also, but it is considered a narrowing conversion and must be done with a cast The widening conversion is the most useful Widening – int to double Narrowing – double to int

9 CSE 1302C Polymorphism via Inheritance It is the type of the object being referenced, not the reference type, that determines which method is invoked (donut hole type, not variable type) Suppose the Holiday class has a method called celebrate, and the Christmas class overrides it

10 CSE 1302C Polymorphism via Inheritance Holiday President’sMine ChristmasBirthday

11 CSE 1302C Polymorphism via Inheritance Now consider the following invocation: day.celebrate(); If day refers to a Holiday object, Holiday day; day.celebrate(); it invokes the Holiday version of celebrate ; If it refers to a Christmas object, Christmas day; day.celebrate(); it invokes the Christmas version

12 CSE 1302C References and Inheritance An object reference can refer to an object of its class, or to an object of any class related to it by inheritance For example, if the Holiday class is used to derive a class called Christmas, then a Holiday reference could be used to point to a Christmas object Holiday day; day = new Christmas(); Holiday Christmas

13 CSE 1302C Polymorphism Requirements To use polymorphism, these conditions must be true: –the classes are in the same hierarchy. –all subclasses override the same method. –a subclass object reference is assigned to a superclass object reference. –the superclass object reference is used to call the method.

14 CSE 1302C abstract Classes and Methods An abstract class is a class that is not completely implemented. Usually, the abstract class contains at least one abstract method. –An abstract method specifies an API but does not provide an implementation. –The abstract method is used as a pattern for a method the subclasses should implement.

15 CSE 1302C Abstract Classes An abstract class often contains abstract methods with no definitions (like an interface) Unlike an interface, the abstract modifier must be applied to each abstract method Also, an abstract class typically contains non- abstract methods with full definitions A class declared as abstract does not have to contain abstract methods -- simply declaring it as abstract makes it so

16 CSE 1302C Abstract Classes The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract An abstract method cannot be defined as const or static The use of abstract classes is an important element of software design – it allows us to establish common elements in a hierarchy that are too generic to instantiate

17 CSE 1302C More on abstract Classes An object reference to an abstract class can be declared. –We use this capability in polymorphism. An abstract class cannot be used to instantiate objects (because the class is not complete). An abstract class can be extended. – subclasses can complete the implementation and objects of those subclasses can be instantiated.

18 CSE 1302C Defining an abstract class To declare a class as abstract, include the abstract keyword in the class header: accessModifier abstract class ClassName { // class body }

19 CSE 1302C Defining an abstract Method To declare a method as abstract, include the abstract keyword in the method header: accessModifier abstract returnType methodName( argument list ); Note: –The semicolon at the end of the header indicates that the method has no code. –We do not use open and closing curly braces

20 CSE 1302C Example Hierarchy We can define a Figure hierarchy. The superclass is Figure, which is abstract. (In the UML diagram, Figure is set in italics to indicate that it is abstract. We will derive two subclasses: Circle and Square.

21 CSE 1302C The Figure Class public abstract class Figure { private int x; private int y; private Color color; // usual constructors, accessors, // and mutators that can be implemented // abstract methods public abstract void draw( Graphics g ); public abstract double area( ); } All classes in the hierarchy will have an (x, y) coordinate and color. Subclasses will implement the draw and area method.

22 CSE 1302C Subclasses of abstract Classes A subclass of an abstract class can implement all, some, or none of the abstract methods. If the subclass does not implement all of the abstract methods, it must also be declared as abstract. Our Circle subclass adds a radius instance variable and implements the draw and area methods. Our Square subclass adds a length instance variable and implements the draw and area methods.

23 CSE 1302C Restrictions for Defining abstract Classes Classes must be declared abstract if the class contains any abstract methods. abstract classes can be extended. An object reference to an abstract class can be declared. abstract classes cannot be used to instantiate objects.

24 CSE 1302C Restrictions for Defining abstract Methods abstract methods can be declared only within an abstract class. An abstract method must consist of a method header followed by a semicolon. abstract methods cannot be called. abstract methods cannot be declared as private or static. A constructor cannot be declared abstract.

25 CSE 1302C Multiple Inheritance C# 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 One problem with multiple inheritance is collisions, such as the same variable name in two parents, which has to be resolved C# does not support multiple inheritance In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead

26 CSE 1302C Interfaces A class can inherit directly from only one class, that is, a class can extend only one class. To allow a class to inherit behavior from multiple sources, C# provides the interface. An interface typically specifies behavior that a class will implement. Interface members can be any of the following:  · classes  · constants  · abstract methods  · other interfaces

27 CSE 1302C Interface Syntax To define an interface, use the following syntax: accessModifier interface InterfaceName { // body of interface } All interfaces are abstract; thus, they cannot be instantiated. The abstract keyword, however, can be omitted in the interface definition.

28 CSE 1302C Interfaces public interface Doable { public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } interface is a reserved word None of the methods in an interface are given a definition (body) A semicolon immediately follows each method header

29 CSE 1302C Finer Points of Interfaces An interface's fields are public, static, and const. These keywords can be specified or omitted. When you define a field in an interface, you must assign a value to the field. All methods within an interface must be abstract, so the method definition must consist of only a method header and a semicolon. The abstract keyword also can be omitted from the method definition.

30 CSE 1302C Inheriting from an Interface To inherit from an interface, a class declares that it implements the interface in the class definition, using the following syntax: accessModifier class ClassName : SuperclassName implements Interface1, Interface2, … The extends clause is optional. A class can implement 0, 1, or more interfaces. When a class implements an interface, the class must provide an implementation for each method in the interface.

31 CSE 1302C Interfaces An interface cannot be instantiated Methods in an interface have public visibility by default A class formally implements an interface by: –stating so in the class header –providing implementations for each abstract method in the interface If a class asserts that it implements an interface, it must define all methods in the interface

32 CSE 1302C Interfaces public class CanDo implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } implements is a reserved word Each method listed in Doable is given a definition

33 CSE 1302C Polymorphism via Interfaces An interface name can be used as the type of an object reference variable Speaker current; The current reference can be used to point to any object of any class that implements the Speaker interface The version of speak that the following line invokes depends on the type of object that current is referencing current.speak();

34 CSE 1302C Polymorphism via Interfaces Suppose two classes, Philosopher and Dog, both implement the Speaker interface, providing distinct versions of the speak method In the following code, the first call to speak invokes one version and the second invokes another: Speaker guest = new Philospher(); guest.speak(); guest = new Dog(); guest.speak();

35 CSE 1302C Interfaces The C# standard class library contains many helpful interfaces The Comparable interface contains one abstract method called compareTo, which is used to compare two objects We know about the compareTo method of the String class The String class implements Comparable, giving us the ability to put strings in lexicographic order

36 CSE 1302C 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 is 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

37 CSE 1302C 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

38 CSE 1302C 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 C# to deal with an object in certain ways Interfaces are a key aspect of object-oriented design in C#

39 CSE 1302C Interface Hierarchies Inheritance can be applied to interfaces as well as classes That is, one interface can be derived from another interface The child interface inherits all abstract methods of the parent A class implementing the child interface must define all methods from both the ancestor and child interfaces Note that class hierarchies and interface hierarchies are distinct (they do not overlap)

40 CSE 1302C Designing for Inheritance As we've discussed, taking the time to create a good software design reaps long-term benefits Inheritance issues are an important part of an object- oriented design Properly designed inheritance relationships can contribute greatly to the elegance, maintainabilty, and reuse of the software Let's summarize some of the issues regarding inheritance that relate to a good software design

41 CSE 1302C Inheritance Design Issues Every derivation should be an is-a relationship Think about the potential future of a class hierarchy, and design classes to be reusable and flexible Find common characteristics of classes and push them as high in the class hierarchy as appropriate Override methods as appropriate to tailor or change the functionality of a child Add new variables to children, but don't redefine (shadow) inherited variables

42 CSE 1302C Inheritance Design Issues Allow each class to manage its own data; use the super reference to invoke the parent's constructor to set up its data Even if there are no current uses for them, override general methods such as toString and equals with appropriate definitions Use abstract classes to represent general concepts that lower classes have in common Use visibility modifiers carefully to provide needed access without violating encapsulation

43 CSE 1302C Program.cs using System; using System.Collections.Generic; using System.Text; namespace _302_inh { class Program { static void Main(string[] args) { Animal a; Dog d = new Dog(); Cat c = new Tabbie(); a = c; a.MakeNoise(); a = d; a.MakeNoise();

44 CSE 1302C Program.cs List zoo = new List(); zoo.Add(d); zoo.Add(c); zoo.Add(new Dog()); foreach (Animal temp in zoo) { temp.MakeNoise(); }

45 CSE 1302C Animal.cs using System; using System.Collections.Generic; using System.Text; namespace _302_inh { abstract class Animal { public abstract void MakeNoise(); public abstract void MakeNoise(int a); public int weight; public Animal() { weight = 10; } public void Sleep() { Console.WriteLine("Zzzz"); }

46 CSE 1302C Dog.cs using System; using System.Collections.Generic; using System.Text; namespace _302_inh { class Dog : Animal { public override void MakeNoise() { Console.WriteLine("Bark"); } public override void MakeNoise(int a) { Console.WriteLine("Bark " + a); } public void Sniff() { Console.WriteLine("Sniff sniff"); }

47 CSE 1302C Cat.cs using System; using System.Collections.Generic; using System.Text; namespace _302_inh { abstract class Cat : Animal { public override void MakeNoise() { Console.WriteLine("Meow"); }

48 CSE 1302C class Tabbie : Cat { public override void MakeNoise(int a) { Console.WriteLine("Purr " + a); }

49 CSE 1302C Questions?