inheritance polymorphism briana b. morrison cse 1302c spring 2010
TRANSCRIPT
Inheritance
Polymorphism
Briana B. MorrisonCSE 1302C
Spring 2010
2CSE 1302C
Topics• Inheritance Concepts• Inheritance Design
– Inherited Members of a Class– Subclass Constructors– Adding Specialization to the Subclass– Overriding Inherited Methods
• The protected Access Modifier
3CSE 1302C
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.
4CSE 1302C
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
5CSE 1302C
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.
6CSE 1302C
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.
7CSE 1302C
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.
8CSE 1302C
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.
9CSE 1302C
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
10CSE 1302C
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
11CSE 1302C
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
12CSE 1302C
The Object ClassThe 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)
13CSE 1302C
Examplenamespace ConsoleApplication1{public class ObjectExample{
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); }}}
public class Temp{ private int a; private char ch;}
Output
This is an object System.Object
This is a temp object ConsoleApplication1.Temp
14CSE 1302C
The Bank Account Hierarchy• The BankAccount class is
the superclass.– Instance variables:
• balance (double)
– Methods:• Default and overloaded constructors• deposit and withdraw methods• balance accessor• toString
15CSE 1302C
ScreenManager Hierarchy• //**pull from A2**//
16CSE 1302C
private Members• Superclass members declared as
private are part of the subclass, but not accessible by the subclass
• /** rework based on a2 **/
17CSE 1302C
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 );
18CSE 1302C
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
19CSE 1302C
Adding Specialization• A subclass can define new fields and
methods.
20CSE 1302C
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.
21CSE 1302C
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 )
22CSE 1302C
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
23CSE 1302C
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.
24CSE 1302C
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.
25CSE 1302C
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.
26CSE 1302C
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.
27CSE 1302C
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 and mutators
no, must call accessors and mutators
private methods yes* - no access
no no
28CSE 1302C
Questions?