Title: CS 112 Introduction to Programming, Spring 2001
1Outline
- Class inheritance why?
- Class inheritance how
- Syntax
- How to control inheritance
2Software Design and Reuse
- Question What features allow us to better
organize a program? - Question What programming language feature we
have covered allows software reuse?
3C Classes
- C classes play dual roles
- Program modules containing a list of (static)
method declarations and (static) data fields - Blueprints for generating objects
- Instance variables (or fields)
- (Dynamic) methods
- Constructors (for building new objects) and
destructors - Properties
- Or a mix of both!
- Classes support inheritance (for code reuse)
and - data encapsulation (e.g., private
components, for abstraction) --- the essence of
object-oriented programming
4Inheritance
- 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 for the parent class
5Inheritance
- Inheritance relationships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class
Inheritance should create an is-a relationship,
meaning the child is a more specific version of
the parent
fly() void
6Inheritance
- 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, 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 for the parent class
7Inheritance
- Inheritance relationships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class
Inheritance should create an is-a relationship,
meaning the child is a more specific version of
the parent
8Base Classes and Derived Classes
9Software Engineering with Inheritance
- Can customize derived classes to meet needs by
- Creating new member variables
- Creating new methods
- Override base-class members
- .NET Framework Class Library(FCL) allows full
reuse of software through inheritance
10Outline
- Class inheritance why?
- Class inheritance how
- Syntax
- How to control inheritance
11Deriving Subclasses
- In Java, we use the reserved word extends to
establish an inheritance relationship - class Animal
-
- // class contents
-
- class Bird extends Animal
-
- // class contents
-
12C Class Declaration
- A class declaration declares a new class Ident
- class-modifiers class Ident base-class
-
- class-member-declarations
-
-
- Sample class modifiers public, protected,
internal, private, abstract, sealed - Base-class the parent class if omitted
the parent is Object
13C Class Member Declarations
- Constant declarations
- modifiers const type ident1
constant-expression1, -
. - identn
constant-expressionn - Modifiers can be private, public, internal,
protected, - Examples public const double X
1.0, Y 2.0, Z 3.0 - Field declarations
- modifiers type ident1
variable-initializer1 , -
. - identn
variable-initializern - Modifiers can be private, public, internal,
protected, - static, readonly
- Examples public static int X 1, Y, Z
100
14C Class Member Declarations (contd)
- Method declarations
- modifiers return-type ident
(formal-parameter-list) -
.. -
method-body -
.. -
- Modifiers can be private, public, internal,
protected, - static,
- new, virtual, sealed, override,
abstract - Note abstract methods may not have a
method body. - Constructor declarations
- modifiers ClsIdent (formal-parameter-list)
constructor-initializer -
.. -
constructor-body -
.. -
15C Class Member Declarations
- Constant declarations
- modifiers const type ident1
constant-expression1, -
. - identn
constant-expressionn - Modifiers can be private, public, internal,
protected, - Examples public const double X
1.0, Y 2.0, Z 3.0 - Field declarations
- modifiers type ident1
variable-initializer1 , -
. - identn
variable-initializern - Modifiers can be private, public, internal,
protected, - static, readonly
- Examples public static int X 1, Y, Z
100
16Outline
- Class inheritance why?
- Class inheritance how
- Syntax
- How to control inheritance
17Controlling Inheritance
- Visibility modifiers determine which class
members get inherited and which do not - Members (variables and methods) declared with
public visibility are inherited, and those with
private visibility are not - Problem public variables violate our goal of
encapsulation - Solution Java provides a third visibility
modifier that helps in inheritance situations
protected
18Controlling Inheritance
- Visibility modifiers determine which class
members get inherited and which do not - Variables and methods declared with public
visibility are inherited, and those with private
visibility are not - But public variables violate our goal of
encapsulation - There is a third visibility modifier that helps
in inheritance situations protected
19protected and internal Members
- protected members
- can be accessed by base class or any class
derived from that base class - internal members
- can only be accessed by classed declared in the
same assembly - Overridden base class members can be accessed
- base.member
20The protected Modifier
- The protected visibility modifier allows a member
of a base class to be inherited into the child - protected visibility provides more encapsulation
than public does - protected visibility is not as tightly
encapsulated as private visibility - The details of each modifier are given in
Appendix F - Example
- Book.java
- Dictionary.java
- TestBookDictionary.java
21Defining Methods in the Child Class 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 is often used to invoke the
parent's constructor - Example1
- See Book2.java
- See Dictionary2.java
- See Words2.java
- Example 2
- See FoodItem.java
- See Pizza.java
- See FoodAnalysis.java
22Defining Methods in the Child Class Overriding
Methods
- A child class can override the definition of an
inherited method in favor of its own - That is, a child can redefine a method that it
inherits from its parent - The new method must have the same signature as
the parent's method, but can have different code
in the body - The type of the object executing the method
determines which version of the method is invoked
23Overriding Methods
- See Thought.java
- See Advice.java
- See Messages.java
- Note
- An overridden parent method can be explicitly
invoked using the super reference at the child - If a method is declared with the final modifier,
it cannot be overridden - The concept of overriding can be applied to data
(called shadowing variables), there is generally
no need for it
24Overloading vs. Overriding
- Overloading deals with multiple methods in the
same class with the same name but different
signatures - Overloading lets you define a similar operation
in different ways for different data
- Overriding deals with two methods, one in a
parent class and one in a child class, that have
the same signature - Overriding lets you define a similar operation in
different ways for different object types
25Review Inheritance
- Inheritance allows a software developer to derive
a new class from an existing one - The visibility modifier protected
- The super reference can be used to refer to the
parent class, and is often used to invoke the
parent's constructor - A child class can override the definition of an
inherited method in favor of its own
26Overloading vs. Overriding
- Overloading deals with multiple methods in the
same class with the same name but different
signatures - Overloading lets you define a similar operation
in different ways for different data
- Overriding deals with two methods, one in a
parent class and one in a child class, that have
the same signature - Overriding lets you define a similar operation in
different ways for different object types
27Outline
- Class hierarchies
- The Object class
- Using class inheritance to implement polymorphism
28Single vs. Multiple Inheritance
- C and Java support 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 - In most cases, the use of interfaces gives us the
best aspects of multiple inheritance without the
overhead
29Class Hierarchies
- Two children of the same parent are called
siblings - Good class design puts all common features as
high in the hierarchy as is reasonable - An inherited member is continually passed down
the line - Class hierarchies often have to be extended and
modified to keep up with changing needs - There is no single class hierarchy that is
appropriate for all situations
30The Object Class
- A class called Object is defined in the C
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 - The Object class is therefore the ultimate root
of all class hierarchies
31The 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 - The Object class is therefore the ultimate root
of all class hierarchies - The Object class contains a few useful methods,
which are inherited by all classes - toString()
- equals()
- clone()
32The Object Class the toString Method
- Thats why the println method can call toString
for any object that is passed to it all objects
are guaranteed to have a toString method via
inheritance - The toString method in the Object class is
defined to return a string that contains the name
of the objects class and a hash value - Every time we have defined toString, we have
actually been overriding it
33The Object Class the equals Method
- The equals method of the Object class determines
if two variables point to the same object (more
shortly) - You may choose to override equals to define
equality in some other way - Example
- See Student.java
- See GradStudent.java
- See Academia.java
34Relationship btw Base- and Derived Classes
- Use a point-circle hierarchy to represent
relationship between base and derived classes - The first thing a derived class does is call its
base class constructor, either explicitly or
implicitly - override keyword is needed if a derived-class
method overrides a base-class method - If a base class method is going to be overridden
it must be declared virtual
35Class Hierarchies
- A child class of one parent can be the parent of
another child, forming class hierarchies
Animal
Reptile
Bird
Mammal
Snake
Lizard
Bat
Horse
Parrot
36More Examples Base Classes and Derived Classes
CommunityMemeber
Employee
Student
Alumnus
Faculty
Staff
Professor
AssistantProfessor
Fig. 9.2 Inheritance hierarchy for university
CommunityMembers.
37Yet More Examples Base Classes and Derived
Classes
Shape
TwoDimensionalShape
ThreeDimensionalShape
Sphere
Cube
Cylinder
Triangle
Square
Circle
Fig. 9.3 Portion of a Shape class hierarchy.
38Class Hierarchies
- Good class design puts all common features as
high in the hierarchy as is reasonable - An inherited member is continually passed down
the lineinheritance is transitive - Class hierarchies often have to be extended and
modified to keep up with changing needs - There is no single class hierarchy that is
appropriate for all situations
39Point.cs
- 1 // Fig. 9.4 Point.cs
- 2 // Point class represents an x-y coordinate
pair. - 3
- 4 using System
- 5
- 6 // Point class definition implicitly
inherits from Object - 7 public class Point
- 8
- 9 // point coordinates
- 10 private int x, y
- 11
- 12 // default (no-argument) constructor
- 13 public Point()
- 14
- 15 // implicit call to Object constructor
occurs here - 16
- 17
- 18 // constructor
- 19 public Point( int xValue, int yValue )
40Point.cs Program Output
- 34 set
- 35
- 36 x value // no need for
validation - 37
- 38
- 39 // end property X
- 40
- 41 // property Y
- 42 public int Y
- 43
- 44 get
- 45
- 46 return y
- 47
- 48
- 49 set
- 50
- 51 y value // no need for
validation - 52
41PointTest.cs
- 1 // Fig. 9.5 PointTest.cs
- 2 // Testing class Point.
- 3
- 4 using System
- 5 using System.Windows.Forms
- 6
- 7 // PointTest class definition
- 8 class PointTest
- 9
- 10 // main entry point for application
- 11 static void Main( string args )
- 12
- 13 // instantiate Point object
- 14 Point point new Point( 72, 115 )
- 15
- 16 // display point coordinates via X and
Y properties - 17 string output "X coordinate is "
point.X - 18 "\n" "Y coordinate is "
point.Y - 19
42Circle.cs
- 1 // Fig. 9.6 Circle.cs
- 2 // Circle class contains x-y coordinate pair
and radius. - 3
- 4 using System
- 5
- 6 // Circle class definition implicitly
inherits from Object - 7 public class Circle
- 8
- 9 private int x, y // coordinates of
Circle's center - 10 private double radius // Circle's radius
- 11
- 12 // default constructor
- 13 public Circle()
- 14
- 15 // implicit call to Object constructor
occurs here - 16
- 17
- 18 // constructor
- 19 public Circle( int xValue, int yValue,
double radiusValue )
43Circle.cs
- 35 set
- 36
- 37 x value // no need for
validation - 38
- 39
- 40 // end property X
- 41
- 42 // property Y
- 43 public int Y
- 44
- 45 get
- 46
- 47 return y
- 48
- 49
- 50 set
- 51
- 52 y value // no need for
validation - 53
44Circle.cs
- 70
- 71 // end property Radius
- 72
- 73 // calculate Circle diameter
- 74 public double Diameter()
- 75
- 76 return radius 2
- 77
- 78
- 79 // calculate Circle circumference
- 80 public double Circumference()
- 81
- 82 return Math.PI Diameter()
- 83
- 84
- 85 // calculate Circle area
- 86 public double Area()
- 87
- 88 return Math.PI Math.Pow( radius, 2
)
45CircleTest.cs
- 1 // Fig. 9.7 CircleTest.cs
- 2 // Testing class Circle.
- 3
- 4 using System
- 5 using System.Windows.Forms
- 6
- 7 // CircleTest class definition
- 8 class CircleTest
- 9
- 10 // main entry point for application.
- 11 static void Main( string args )
- 12
- 13 // instantiate Circle
- 14 Circle circle new Circle( 37, 43,
2.5 ) - 15
- 16 // get Circle's initial x-y
coordinates and radius - 17 string output "X coordinate is "
circle.X - 18 "\nY coordinate is " circle.Y
"\nRadius is " - 19 circle.Radius
46CircleTest.cs
- 34 // display Circle's circumference
- 35 output "Circumference is "
- 36 String.Format( "0F",
circle.Circumference() ) "\n" - 37
- 38 // display Circle's area
- 39 output "Area is "
- 40 String.Format( "0F",
circle.Area() ) - 41
- 42 MessageBox.Show( output,
"Demonstrating Class Circle" ) - 43
- 44 // end method Main
- 45
- 46 // end class CircleTest
47Circle2.cs
- 1 // Fig. 9.8 Circle2.cs
- 2 // Circle2 class that inherits from class
Point. - 3
- 4 using System
- 5
- 6 // Circle2 class definition inherits from
Point - 7 class Circle2 Point
- 8
- 9 private double radius // Circle2's
radius - 10
- 11 // default constructor
- 12 public Circle2()
- 13
- 14 // implicit call to Point constructor
occurs here - 15
- 16
- 17 // constructor
- 18 public Circle2( int xValue, int yValue,
double radiusValue ) - 19
48Circle2.cs
- 34 set
- 35
- 36 if ( value gt 0 )
- 37 radius value
- 38
- 39
- 40 // end property Radius
- 41
- 42 // calculate Circle diameter
- 43 public double Diameter()
- 44
- 45 return radius 2
- 46
- 47
- 48 // calculate Circle circumference
- 49 public double Circumference()
- 50
- 51 return Math.PI Diameter()
- 52
49Circle2.cs program output
50Point2.cs
- 1 // Fig. 9.9 Point2.cs
- 2 // Point2 class contains an x-y coordinate
pair as protected data. - 3
- 4 using System
- 5
- 6 // Point2 class definition implicitly
inherits from Object - 7 public class Point2
- 8
- 9 // point coordinate
- 10 protected int x, y
- 11
- 12 // default constructor
- 13 public Point2()
- 14
- 15 // implicit call to Object constructor
occurs here - 16
- 17
- 18 // constructor
- 19 public Point2( int xValue, int yValue )
51Point2.cs
- 34 set
- 35
- 36 x value // no need for
validation - 37
- 38
- 39 // end property X
- 40
- 41 // property Y
- 42 public int Y
- 43
- 44 get
- 45
- 46 return y
- 47
- 48
- 49 set
- 50
- 51 y value // no need for
validation - 52
52Circle3.cs
- 1 // Fig. 9.10 Circle3.cs
- 2 // Circle2 class that inherits from class
Point2. - 3
- 4 using System
- 5
- 6 // Circle3 class definition inherits from
Point2 - 7 public class Circle3 Point2
- 8
- 9 private double radius // Circle's radius
- 10
- 11 // default constructor
- 12 public Circle3()
- 13
- 14 // implicit call to Point constructor
occurs here - 15
- 16
- 17 // constructor
- 18 public Circle3(
- 19 int xValue, int yValue, double
radiusValue )
53Circle3.cs
- 35 set
- 36
- 37 if ( value gt 0 )
- 38 radius value
- 39
- 40
- 41 // end property Radius
- 42
- 43 // calculate Circle diameter
- 44 public double Diameter()
- 45
- 46 return radius 2
- 47
- 48
- 49 // calculate circumference
- 50 public double Circumference()
- 51
- 52 return Math.PI Diameter()
- 53
54CircleTest3.cs
- 1 / Fig. 9.11 CircleTest3.cs
- 2 // Testing class Circle3.
- 3
- 4 using System
- 5 using System.Windows.Forms
- 6
- 7 // CircleTest3 class definition
- 8 class CircleTest3
- 9
- 10 // main entry point for application
- 11 static void Main( string args )
- 12
- 13 // instantiate Circle3
- 14 Circle3 circle new Circle3( 37, 43,
2.5 ) - 15
- 16 // get Circle3's initial x-y
coordinates and radius - 17 string output "X coordinate is "
circle.X "\n" - 18 "Y coordinate is " circle.Y
"\nRadius is " - 19 circle.Radius
55CircleTest3.cs
- 35 // display Circle3's Circumference
- 36 output "Circumference is "
- 37 String.Format( "0F",
circle.Circumference() ) "\n" - 38
- 39 // display Circle3's Area
- 40 output "Area is "
- 41 String.Format( "0F",
circle.Area() ) - 42
- 43 MessageBox.Show( output,
"Demonstrating Class Circle3" ) - 44
- 45 // end method Main
- 46
- 47 // end class CircleTest3
56Point3.cs
- 1 // Fig. 9.12 Point3.cs
- 2 // Point3 class represents an x-y coordinate
pair. - 3
- 4 using System
- 5
- 6 // Point3 class definition implicitly
inherits from Object - 7 public class Point3
- 8
- 9 // point coordinate
- 10 private int x, y
- 11
- 12 // default constructor
- 13 public Point3()
- 14
- 15 // implicit call to Object constructor
occurs here - 16
- 17
- 18 // constructor
- 19 public Point3( int xValue, int yValue )
57Point3.cs
- 34 set
- 35
- 36 x value // no need for
validation - 37
- 38
- 39 // end property X
- 40
- 41 // property Y
- 42 public int Y
- 43
- 44 get
- 45
- 46 return y
- 47
- 48
- 49 set
- 50
- 51 y value // no need for
validation - 52
58Circle4.cs
- 1 // Fig. 9.13 Circle4.cs
- 2 // Circle4 class that inherits from class
Point3. - 3
- 4 using System
- 5
- 6 // Circle4 class definition inherits from
Point3 - 7 public class Circle4 Point3
- 8
- 9 private double radius
- 10
- 11 // default constructor
- 12 public Circle4()
- 13
- 14 // implicit call to Point constructor
occurs here - 15
- 16
- 17 // constructor
- 18 public Circle4( int xValue, int yValue,
double radiusValue ) - 19 base( xValue, yValue )
59Circle4.cs
- 36
- 37
- 38 // end property Radius
- 39
- 40 // calculate Circle diameter
- 41 public double Diameter()
- 42
- 43 return Radius 2 // use property
Radius - 44
- 45
- 46 // calculate Circle circumference
- 47 public double Circumference()
- 48
- 49 return Math.PI Diameter()
- 50
- 51
- 52 // calculate Circle area
- 53 public virtual double Area()
- 54
60CircleTest4.cs
- 1 // Fig. 9.14 CircleTest4.cs
- 2 // Testing class Circle4.
- 3
- 4 using System
- 5 using System.Windows.Forms
- 6
- 7 // CircleTest4 class definition
- 8 class CircleTest4
- 9
- 10 // main entry point for application
- 11 static void Main( string args )
- 12
- 13 // instantiate Circle4
- 14 Circle4 circle new Circle4( 37, 43,
2.5 ) - 15
- 16 // get Circle4's initial x-y
coordinates and radius - 17 string output "X coordinate is "
circle.X "\n" - 18 "Y coordinate is " circle.Y
"\n" - 19 "Radius is " circle.Radius
61CircleTest4.cs
- 35 // display Circle4's Circumference
- 36 output "Circumference is "
- 37 String.Format( "0F",
circle.Circumference() ) "\n" - 38
- 39 // display Circle4's Area
- 40 output "Area is "
- 41 String.Format( "0F",
circle.Area() ) - 42
- 43 MessageBox.Show( output,
"Demonstrating Class Circle4" ) - 44
- 45 // end method Main
- 46
- 47 // end class CircleTest4
62Case Study Three-Level Inheritance Hierarchy
- Three-level inheritance example
- Class Cylinder inherits from class Circle4
- Class Circle4 inherits from class Point3
63Cylinder.cs
- 1 // Fig. 9.15 Cylinder.cs
- 2 // Cylinder class inherits from class
Circle4. - 3
- 4 using System
- 5
- 6 // Cylinder class definition inherits from
Circle4 - 7 public class Cylinder Circle4
- 8
- 9 private double height
- 10
- 11 // default constructor
- 12 public Cylinder()
- 13
- 14 // implicit call to Circle4
constructor occurs here - 15
- 16
- 17 // four-argument constructor
- 18 public Cylinder( int xValue, int yValue,
double radiusValue, - 19 double heightValue ) base( xValue,
yValue, radiusValue )
64Cylinder.cs
- 36
- 37
- 38 // end property Height
- 39
- 40 // override Circle4 method Area to
calculate Cylinder area - 41 public override double Area()
- 42
- 43 return 2 base.Area()
base.Circumference() Height - 44
- 45
- 46 // calculate Cylinder volume
- 47 public double Volume()
- 48
- 49 return base.Area() Height
- 50
- 51
- 52 // convert Cylinder to string
- 53 public override string ToString()
- 54
65CylinderTest.cs
- 1 // Fig. 9.16 CylinderTest.cs
- 2 // Tests class Cylinder.
- 3
- 4 using System
- 5 using System.Windows.Forms
- 6
- 7 // CylinderTest class definition
- 8 class CylinderTest
- 9
- 10 // main entry point for application
- 11 static void Main( string args )
- 12
- 13 // instantiate object of class
Cylinder - 14 Cylinder cylinder new Cylinder(12,
23, 2.5, 5.7) - 15
- 16 // properties get initial x-y
coordinate, radius and height - 17 string output "X coordinate is "
cylinder.X "\n" - 18 "Y coordinate is " cylinder.Y
"\nRadius is " - 19 cylinder.Radius "\n" "Height is
" cylinder.Height
66CylinderTest.cs
- 35 // display Cylinder's Circumference
- 36 output "Circumference is "
- 37 String.Format( "0F",
cylinder.Circumference() ) "\n" - 38
- 39 // display Cylinder's Area
- 40 output "Area is "
- 41 String.Format( "0F",
cylinder.Area() ) "\n" - 42
- 43 // display Cylinder's Volume
- 44 output "Volume is "
- 45 String.Format( "0F",
cylinder.Volume() ) - 46
- 47 MessageBox.Show( output,
"Demonstrating Class Cylinder" ) - 48
- 49 // end method Main
- 50
- 51 // end class CylinderTest
67Abstract Classes
- Java allows abstract classes
- Use the modifier abstract on a class header to
declare an abstract class abstract class
Vehicle - An abstract class is a placeholder in a class
hierarchy that represents a generic concept
Vehicle
Car
Boat
Plane
68Constructors and Destructors in Derived Classes
- Instantiating a derived class, causes base class
constructor to be called, implicitly or
explicitly - Can cause chain reaction when a base class is
also a derived class - When a destructor is called, it performs its task
and then invokes the derived class base class
constructor
69Point4.cs
- 1 // Fig. 9.17 Point4.cs
- 2 // Point4 class represents an x-y coordinate
pair. - 3
- 4 using System
- 5
- 6 // Point4 class definition
- 7 public class Point4
- 8
- 9 // point coordinate
- 10 private int x, y
- 11
- 12 // default constructor
- 13 public Point4()
- 14
- 15 // implicit call to Object constructor
occurs here - 16 Console.WriteLine( "Point4
constructor 0", this ) - 17
- 18
- 19 // constructor
70Point4.cs
- 36
- 37 get
- 38
- 39 return x
- 40
- 41
- 42 set
- 43
- 44 x value // no need for
validation - 45
- 46
- 47 // end property X
- 48
- 49 // property Y
- 50 public int Y
- 51
- 52 get
- 53
- 54 return y
71Circle5.cs
- 1 // Fig. 9.18 Circle5.cs
- 2 // Circle5 class that inherits from class
Point4. - 3
- 4 using System
- 5
- 6 // Circle5 class definition inherits from
Point4 - 7 public class Circle5 Point4
- 8
- 9 private double radius
- 10
- 11 // default constructor
- 12 public Circle5()
- 13
- 14 // implicit call to Point3 constructor
occurs here - 15 Console.WriteLine( "Circle5
constructor 0", this ) - 16
- 17
- 18 // constructor
- 19 public Circle5( int xValue, int yValue,
double radiusValue )
72Circle5.cs
- 35 get
- 36
- 37 return radius
- 38
- 39
- 40 set
- 41
- 42 if ( value gt 0 )
- 43 radius value
- 44
- 45
- 46 // end property Radius
- 47
- 48 // calculate Circle5 diameter
- 49 public double Diameter()
- 50
- 51 return Radius 2
- 52
- 53
73Circle5.cs
- 69 // use base reference to return Point3
string - 70 return "Center " base.ToString()
- 71 " Radius " Radius
- 72
- 73
- 74 // end class Circle5
74ConstructorAndDestructor.cs
- 1 // Fig. 9.19 ConstructorAndDestructor.cs
- 2 // Display order in which base-class and
derived-class constructors - 3 // and destructors are called.
- 4
- 5 using System
- 6
- 7 // ConstructorAndFinalizer class definition
- 8 class ConstructorAndFinalizer
- 9
- 10 // main entry point for application.
- 11 static void Main( string args )
- 12
- 13 Circle5 circle1, circle2
- 14
- 15 // instantiate objects
- 16 circle1 new Circle5( 72, 29, 4.5 )
- 17 circle2 new Circle5( 5, 5, 10 )
- 18
- 19 Console.WriteLine()
75ConstructorAndDestructor.cs program output
- Point4 constructor Center 72, 29 Radius 0
- Circle5 constructor Center 72, 29 Radius
4.5 - Point4 constructor Center 5, 5 Radius 0
- Circle5 constructor Center 5, 5 Radius 10
- Â
- Circle5 destructor Center 5, 5 Radius 10
- Point4 destructor Center 5, 5 Radius 10
- Circle5 destructor Center 72, 29 Radius
4.5 - Point4 destructor Center 72, 29 Radius
4.5
76Outline
- Admin. and review
- Class hierarchies
- The Object class
- Object references
- Using class inheritance to implement polymorphism
77References 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 child class called Christmas, then a
Holiday reference could actually be used to point
to a Christmas object
Holiday
Holiday day day new Holiday() day new
Christmas()
Christmas
78References and Inheritance
- Assigning an object to an ancestor reference is
considered to be a widening conversion, and can
be performed by simple assignment - Assigning an ancestor object to a reference can
also be done, but it is considered to be a
narrowing conversion and must be done with a cast - The widening conversion is the most useful
- For implementing polymorphism
Holiday day new Christmas()
Christmas christ new Christmas() Holiday day
christ Christmas christ2 (Christmas)day
79What is Polymorphism?
- A polymorphic reference is one which can refer to
different types of objects at different times - An object reference can refer to one object at
one time, then it can be changed to refer to
another object (related by inheritance) at
another time
80Polymorphism via Inheritance
- It is the type of the object being referenced,
not the reference type, that determines which
method is invoked - Polymorphic references are therefore resolved at
run-time, not during compilation this is called
dynamic binding - Careful use of polymorphic references can lead to
elegant, robust software designs
81Polymorphism via Inheritance
- Inheritance can be used as a basis of
polymorphism - Suppose the Holiday class has a method called
celebrate, and the Christmas class overrode it - Now consider the following invocation
- day.celebrate()
- If day refers to a Holiday object, it invokes the
Holiday version of celebrate if it refers to a
Christmas object, it invokes the Christmas version
82Example Polymorphism via Inheritance
83Polymorphism via Inheritance and Arrays of Objects
- Now consider the task of paying all employees
- See StaffMember.java (page 414)
- See Volunteer.java (page 415)
- See Employee.java (page 416)
- See Executive.java (page 417)
- See Hourly.java (page 418)
- See Firm.java (page 410)
- See Staff.java (page 412)
84Outline
- Admin. and review
- Interface overview
- Interface hierarchies
- Using interface to implement polymorphism
85Review
- Class inheritance
- What are inherited? FoodItem, Pizza
- Method overriding
- Class hierarchies
- Abstract classes
- The Object classhttp//java.sun.com/j2se/1.4/docs
/api/java/lang/Object.html - Object references
- Polymorphism via inheritance and an array of base
objects
86(No Transcript)
87Outline
- Admin. and review
- Interface overview
- Interface hierarchies
- Using interface to implement polymorphism
88Single vs. Multiple Inheritance
- Some object-oriented languages allow Multiple
inheritance, which allows a class to be derived
from two or more classes, inheriting the members
of all parents - The price collisions, such as the same variable
name in two parents, have to be resolved - Java decision single inheritance, meaning that a
derived class can have only one parent class - To take the advantages of multiple inheritance,
Java defines interfaces, which give us the best
aspects of multiple inheritance without the
overhead
89Java Interface
- A Java interface is a collection of constants
and abstract methods - An abstract method is a method header without a
method body - An abstract method can be declared using the
modifier abstract, but because all methods in an
interface are abstract, it is usually left off - An interface is used to formally define a set of
methods that a class will implement
90Interfaces Syntax
public interface Doable public static final
String NAME public void doThis() public
int doThat() public void doThis2 (float
value, char ch) public boolean doTheOther
(int num)
No method in an interface has a definition (body)
91Interfaces
- 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 in the implements
clause - A class can implement multiple interfaces the
interfaces are listed in the implements clause,
separated by commas - If a class asserts that it implements an
interface, it must define all methods in the
interface or the compiler will produce errors
92Implementing Interfaces
public class CanDo implements Doable public
void doThis () // whatever
public void doThat () // whatever
// etc.
public class ManyThings implements Doable,
AnotherDoable
93Interfaces An Example
- A class that implements an interface can
implement other methods as well - See Complexity.java (page 294)
- See Question.java (page 295)
- See MinQuiz.java (page 297)
94UML Diagram
ltltinterfacegtgt Complexity
getComplexity () int setComplexity (int)
void
1
2
Question
getQuestion () String getAnswer ()
String answerCorrect (String) boolean
toString() String
95Interfaces Examples from Java Standard Class
Library
- The Java standard class library contains many
interfaces that are helpful in certain situations - The Comparable interface contains an abstract
method called compareTo, which is used to compare
two objects - if (obj1.compareTo(obj2) lt 0)
System.out.println(obj1 is less than obj2) - The String class implements Comparable which
gives us the ability to put strings in
alphabetical order - The Iterator interface contains methods that
allow the user to move through a collection of
objects easily - hasNext(), next(), remove()
96Outline
- Admin. and review
- Interface overview
- Interface hierarchies
- Using interface to implement polymorphism
97Interface Hierarchies
- Inheritance can be applied to interfaces as well
as classes - One interface can be used as the parent of
another - The child interface inherits all abstract methods
of the parent - A class implementing the child interface must
define all methods from both the parent and child
interfaces - Note that class hierarchies and interface
hierarchies are distinct (they do not overlap)
98Outline
- Admin. and review
- Interface overview
- Interface hierarchies
- Using interface to implement polymorphism
99Polymorphism via Interfaces
- An interface name can be used as the type of an
object reference variable - Doable obj
- The obj reference can be used to point to any
object of any class that implements the Doable
interface - The version of doThis that the following line
invokes depends on the type of object that obj is
referring to - obj.doThis()
100Examples
- public interface Speaker
-
- public void speak()
-
- class Philosopher extends Human implements
Speaker -
- //
- public void speak()
- public void pontificate()
-
-
- class Dog extends Animal implements Speaker
-
- //
- public void speak()
-
-
- Speaker guest
- guest new Philosopher()
- guest.speak()
- guest Dog()
- guest.speak()
Speaker special special new Philosopher() spe
cial.pontificate()
// compiler error
Speaker special special new Philosopher() ((P
hilosopher)special).pontificate()