Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010 Topics • Inheritance Concepts • Inheritance Design – Inherited Members of a Class – Subclass Constructors – Adding Specialization to the Subclass – Overriding Inherited Methods • The protected Access Modifier CSE 1302C 2 Inheritance Concepts • A common form of reuse of classes is inheritance. • We can organize classes into hierarchies of functionality. • The class at the top of the hierarchy (superclass) defines instance variables and methods common to all classes in the hierarchy. • We derive a subclass, which inherits behavior and fields from the superclass. CSE 1302C 3 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, subclass, or derived class • 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 CSE 1302C 4 A Sample Vehicle Hierarchy • This hierarchy is depicted using a Unified Modeling Language (UML) diagram. • In UML diagrams, arrows point from the subclass to the superclass. CSE 1302C 5 Superclasses and Subclasses • A superclass can have multiple subclasses. • Subclasses can be superclasses of other subclasses. • A subclass can inherit directly from only one superclass. • All classes inherit from the Object class. CSE 1302C 6 Superclasses and Subclasses • A big advantage of inheritance is that we can write common code once and reuse it in subclasses. • A subclass can define new methods and instance variables, some of which may override (hide) those of a superclass. CSE 1302C 7 Specifying Inheritance • The syntax for defining a subclass is to use the : symbol in the class header, as in accessModifier class SubclassName: SuperclassName { // class definition } • The superclass name specified after the : is called the direct superclass. • As mentioned, a subclass can have many superclasses, but only one direct superclass. CSE 1302C 8 Class Hierarchies • A child class of one parent can be the parent of another child, forming a class hierarchy Business RetailBusiness KMart CSE 1302C Macys ServiceBusiness Kinkos 9 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 CSE 1302C 10 The Object Class • A class called Object exists • 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 CSE 1302C 11 The Object Class The Object class contains a few useful methods, which are inherited by all classes: • Constructor • Equals • GetHashCode • GetType • ReferenceEquals • ToString (virtual) • Finalize (overridden, destructor) • MemberwiseClone (shallow copy of object) CSE 1302C 12 namespace ConsoleApplication1 public class Temp { { private int a; public class ObjectExample private char ch; { } static void Main(string[] args) { Object o1 = new Object(); Console.WriteLine("This is an object " + o1); Temp t = new Temp(); Console.WriteLine("This is a temp object " + t); } } } Example Output This is an object System.Object This is a temp object ConsoleApplication1.Temp CSE 1302C 13 The Bank Account Hierarchy • The BankAccount class is the superclass. – Instance variables: • balance (double) – Methods: • • • • CSE 1302C Default and overloaded constructors deposit and withdraw methods balance accessor toString 14 ScreenManager Hierarchy • //**pull from A2**// CSE 1302C 15 private Members • Superclass members declared as private are part of the subclass, but not accessible by the subclass • /** rework based on a2 **/ CSE 1302C 16 Subclass Constructors • Constructors are not inherited. • The first task of a constructor is to call a base class constructor. • Use this syntax: base( argument list ); • Or: public constructor(arg1 list):base( argument list ); CSE 1302C 17 The base Reference • A child’s constructor is responsible for calling the parent’s constructor • Normally the first line of a child’s constructor should use the base reference to call the parent’s constructor • The base reference can also be used to reference other variables and methods defined in the parent’s class CSE 1302C 18 Adding Specialization • A subclass can define new fields and methods. CSE 1302C 19 Software Engineering Tip The superclasses in a class hierarchy should contain fields and methods common to all subclasses. The subclasses should add specialized fields and methods. CSE 1302C 20 Overriding Inherited Methods • A subclass can override (or replace) an inherited method by providing a new version of the method. • Base class must include virtual • Descendant must include override • The API of the new version must match the inherited method. • When the client calls the method, it will call the overridden version. • The overridden (original) method is invisible to the client of the subclass, but the subclass methods can still call the overridden (original) method using this syntax: base.methodName( argument list ) CSE 1302C 21 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 CSE 1302C 22 Common Error Trap • Do not confuse overriding a method with overloading a method. • Overriding a method: – A subclass provides a new version of that method (same signature), which hides the superclass version from the client. • Overloading a method: – A class provides a version of the method, which varies in the number and/or type of parameters (different signature). A client of the class can call any of the public versions of overloaded methods. CSE 1302C 23 protected Members • protected members are accessible by subclasses (like public members), while still being hidden from client classes (like private members). • Also, any class in the same package as the superclass can directly access a protected field, even if that class is not a subclass. • Disadvantage: – Because more than one class can directly access a protected field, protected access compromises encapsulation and complicates maintenance of a program. – For that reason, try to use private, rather than protected, for instance variables. CSE 1302C 24 The protected Access Modifier • Declaring fields as private preserves encapsulation. – Subclass methods call superclass methods to set the values of the fields, and the superclass methods enforce the validation rules for the data. – But calling methods incurs processing overhead. • Declaring fields as protected allows them to be accessed directly by subclass methods. – Classes outside the hierarchy and package must use accessors and mutators for protected fields. CSE 1302C 25 protected fields: Tradeoffs • Advantage: – protected fields can be accessed directly by subclasses, so there is no method-invocation overhead. • Disadvantage: – Maintenance is complicated because the subclass also needs to enforce validation rules. • Recommendation: – Define protected fields only when high performance is necessary. – Avoid directly setting the values of protected fields in the subclass. CSE 1302C 26 Inheritance Rules Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass? public fields yes yes, by using field name yes public methods yes yes, by calling method from subclass methods yes protected fields yes yes, by using field name no, must call accessors and mutators protected methods yes yes, by calling method from subclass methods no private fields yes* - no access no, must call accessors no, must call accessors and mutators and mutators private methods yes* - no access CSE 1302C no no 27 Questions? CSE 1302C 28