inheritance superclass base parent subclass derived...

25
Visual C# - Penn P. Wu, PhD. 273 Lecture #9 Inheritance, Composition, and Polymorphism What is inheritance? In biology, the term inheritancerefers to attributes acquired via biological heredity from the parents. In a society, inheritance is the practice of passing on property, titles, debts, and obligations upon the death of an individual. However, in object-oriented programming, inheritance refers to creating a new class (called the superclass or base class or parent class) and sharing its class members with other classes (called the subclass or derived class or child class). Inheritance is an important object-oriented concept. It allows developers to build a hierarchy of related classes, and to reuse functionality defined in existing classes. In a nutshell, inheritance is built based on the an “IS-A” relationship. When on object is a specialized version of another object, there is an “IS-A” relationship between them. For example, a grasshopper is an insect. A grasshopper is a specialized subset of insects while insect is a generalized term of grasshopper. Conceptually, class Insects is a generalization of class Grasshoppers if every Grasshoppers object is also an Insects object. From the perspective of biology, everything that is true about an insect should have is also true for a grasshopper. The “is-a” relationship is a unilateral (one-directional) relationship. It is only true from the specialized subset to the set. A grasshopper is an insect, but an insect may not be a grasshopper. A cricket is an insect, too. One significant advantage of inheritance is that multiple specialized classes, such as “Grasshoppers” and “Crickets”, can inherit members of one single generalized class (Insects). The following illustrates how the five basic physical characteristics of “Insects” apply to “Grasshoppers” and “Crickets”. Inheritance involves a base classand a derived class. The base class is the general class (insect) and the derived class is the specialized class (grasshopper). Therefore, in C#, inheritance is all about building a derived class that inherits attributes and methods from the base class. C# inheritance One of the fundamental activities of object-oriented programming is establishing relationships between classes. In object-oriented programming, the relationship happens when two classes interact with each other. Two fundamental types of relationships between classes are inheritance (“is-a”) and composition (has-a). They could be confusing to students. Insects have five basic physical characteristics: Insects have what we call an exoskeleton or a hard, shell-like covering on the outside of its body. Insects have three main body parts: head, thorax, and abdomen. Insects have a pair of antennae on top of their heads. Insects have three pairs of legs. They use the legs for walking, but sometimes an insect may have a pair of legs that are specially designed for jumping. Insects have two pairs of wings. Grasshoppers Crickets Insects Grasshoppers Crickets

Transcript of inheritance superclass base parent subclass derived...

Page 1: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 273

Lecture #9 Inheritance, Composition, and Polymorphism

What is

inheritance?

In biology, the term “inheritance” refers to attributes acquired via biological heredity from the

parents. In a society, inheritance is the practice of passing on property, titles, debts, and

obligations upon the death of an individual. However, in object-oriented programming,

inheritance refers to creating a new class (called the superclass or base class or parent class)

and sharing its class members with other classes (called the subclass or derived class or child class).

Inheritance is an important object-oriented concept. It allows developers to build a hierarchy of

related classes, and to reuse functionality defined in existing classes. In a nutshell, inheritance is

built based on the an “IS-A” relationship. When on object is a specialized version of another

object, there is an “IS-A” relationship between them. For example, a grasshopper is an insect. A

grasshopper is a specialized subset of insects while insect is a generalized term of grasshopper.

Conceptually, class Insects is a generalization of class Grasshoppers if every Grasshoppers

object is also an Insects object. From the perspective of biology, everything that is true about an

insect should have is also true for a grasshopper.

The “is-a” relationship is a unilateral (one-directional) relationship. It is only true from the

specialized subset to the set. A grasshopper is an insect, but an insect may not be a grasshopper.

A cricket is an insect, too.

One significant advantage of inheritance is that multiple specialized classes, such as “Grasshoppers” and “Crickets”, can inherit members of one single generalized class (Insects).

The following illustrates how the five basic physical characteristics of “Insects” apply to

“Grasshoppers” and “Crickets”.

Inheritance involves a “base class” and a “derived class”. The base class is the general class

(insect) and the derived class is the specialized class (grasshopper). Therefore, in C#,

inheritance is all about building a derived class that inherits attributes and methods from the

base class.

C# inheritance One of the fundamental activities of object-oriented programming is establishing relationships

between classes. In object-oriented programming, the relationship happens when two classes

interact with each other. Two fundamental types of relationships between classes are

inheritance (“is-a”) and composition (“has-a”). They could be confusing to students.

Insects have five basic physical characteristics:

• Insects have what we call an exoskeleton or a hard, shell-like

covering on the outside of its body.

• Insects have three main body parts: head, thorax, and abdomen.

• Insects have a pair of antennae on top of their heads.

• Insects have three pairs of legs. They use the legs for walking,

but sometimes an insect may have a pair of legs that are

specially designed for jumping.

• Insects have two pairs of wings.

Grasshoppers

Crickets

Insects

Grasshoppers Crickets

Page 2: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 274

In C#, inheritance is the performed by defining a base class that provides specific functionality

(data and behavior) and then defining one or more derived class(es) that either inherit or

override that functionality. Composition describes an ownership such as a smartphone has a

microprocessor which also means a smartphone owns the microprocessor. Composition is

practically done by letting one class containing members of another class. The following figure illustrates the difference between immittance and composition.

Inheritance (“is-a”) Composition (“has-a”)

In C#, an inheritance relationship between two classes can be defined using the following syntax which allows the “derived” class to inherit members from the “base” class.

class derived : base { }

The following defines a base class named “B”, which is the inherited by a derived class named

“D”. The relationship is denoted as D : B which also indicates the “D is a B” relationship.

Base class Derived class

public class B

{

}

public class D : B

{

}

Students will encounter an interesting phenomenon in which a “base class” is also known as a

“superclass” or a “parent class” while a “derived class” is also known as a “subclass” or “child

class”. Therefore, “B” is the “superclass” of “D” and “D” is the “subclass” of “B”. “B” is the

“parent class” of “D” and “D” is the “child class” of “B”.

In the following example, the Cat class is a specialized subset of the Animal class through the

defined C# inheritance relationship. Anyway, it is biologically true that a cat is a kind of

animal. The “Main()” function of the “Example” class demonstrates how to create instances of

these two classes.

public class Animal // superclass

{

}

public class Cat : Animal // subclass

{

}

public class Example

{

public static void Main()

base

derived1 derived2

composite

compoent

1

compoent

2

B D

Page 3: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 275

{

Cat c1 = new Cat();

Animal c2 = new Animal();

Animal c3 = new Cat();

Cat c4 = new Animal(); // invalid

}

}

Apparently, developers can create instances of both superclass and subclass, such as “c1” and

“c2” in the above example. However, developers must respect the principle of “is-a”

relationship--the relationship is only true from a subclass to superclass. Since, the subclass (Cat)

is part of the superclass (Animal), developers can claim that “a cat is an animal!”. For example,

“c3” is declared as an instance of superclass but is specialized to an instance of the subclass.

However, since “an animal is not always a cat!”, developers cannot generalize “c4” from a

subclass to superclass. It is an invalid instantiation.

The following statement causes an error message.

Statement Error message Cat c4 = new Animal(); error CS0266: Cannot implicitly

convert type 'Animal' to 'Cat'. An

explicit conversion exists (are you

missing a cast?)

Inheriting

public

members from

the base class

A subclass (derived class) can inherit all the “public” members from the superclass (base class).

In the following example, the “Cat” class has four members: (1) one private variable named

“name” of string type whose default is “Animal”, (2) one public variable named “sound” of

string type whose default value is “screams”, (3) one private function named “”, and (4) one public function name “run()” of string type. The subclass, “Cat”, is an empty class because it

does not have any definition. The “Cat” class simply inherits all public members from the

“Animal” class.

using System;

using System.Windows.Forms;

public class Animal // superclass

{

private string category = "kingdom"; // not shared

public string sound = "screams";

private void mutate() { MessageBox.Show("Mutation happens."); }

public string run() { return name + " can run!"; }

}

public class Cat : Animal { } // empty subclass

public class Example

{

public static void Main()

{

Cat c1 = new Cat(); // instance of subclass

MessageBox.Show( c1.sound + "\n" + c1.run() ); //inheritance

}

}

Page 4: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 276

In the above code, the “inheritance” allows the subclass, “Cat”, to immediately access two

public members, the “sound” variable and the “run” function, of the superclass and use them as

if they are members of the “Cat” class.

The following is an illegal inheritance and will be prohibited because both “name” and “mutation()” are private members of the superclass. They are inaccessible from a subclass.

public static void Main()

{

Cat c1 = new Cat(); // instance of subclass

MessageBox.Show( c1.name + "\n" + c1.mutate() ); //illegal

}

By the way, a variable of a class is known as an “instance variable” while a function of a class

is known as a “method”.

Overriding a

member

In terms of object-oriented programming language, overriding is a feature that allows a

subclass to provide a provide different implementation of a method that is defined by the

superclasses.

In the following example, the superclass contains a public “eat()” function with a defined

feature. The subclass inherits the “eat()” function from the superclass, yet, the subclass has a

different implementation.

public class Animal // superclass

{

public void eat() { MessageBox.Show("Animal eats

predators."); }

}

public class Cat : Animal // subclass

{

public void eat() { MessageBox.Show("Cats eat rats."); }

}

Since the overriding of “Cat.eat()” intends to override an inherited member “Animal.eat()”, C#

compiler suggests to use the new keyword if the overriding is intended. The new keyword

preserves the relationships.

public class Animal // superclass

{

public void eat() { MessageBox.Show("Animal eats

predators."); }

}

public class Cat : Animal // subclass

{

public new void eat() { MessageBox.Show("Cats eat rats."); }

}

The following demonstrates how the new keyword preserves the relationship. The “eat()”

method has been overridden by the subclass because it is given a completely different

implementation. However, the instructor purposely use the base keyword to call the superclass’

version of “eat()”. The base keyword is used to call a method on the superclass that has been

overridden by the subclass.

public class Cat : Animal // subclass

{

Page 5: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 277

public new void eat()

{

base.eat(); // call the superclass’ version

}

}

In C#, a method in a subclass can have the same name as a method in the superclass. However,

whenever there is a need to call the superclass’ version, developers can use the base keyword.

The use of

base() function

to inherit

constructor(s)

Interestingly, inheritance in C# has a rigid principle to follow. If a superclass contains a

constructor, the subclass must have an appropriate re-declaration of the constructor using the

base() function; otherwise, the compiler will flag an error.

A C# subclass can inherit accessible members from its superclass. However, the constructor of

the superclass is not inherited automatically. A constructor is used to construct an instance of a class. Unlike properties and methods, constructors are not inherited; they cannot be invoked

from the subclass. The constructor in a superclass can only be called by its subclasses through

the use of base() method. The base() function is used to specify which superclass constructor to

call when creating instances of the subclass. The syntax is:

SubclassMethod() : base() {}

or

SubclassMethod() : base(parameters) {}

The following demonstrates how to use the base() function to regulate the default constructor of

the subclass.

public class Animal // superclass

{

public Animal() { }

}

public class Cat : Animal // subclass

{

public Cat() : base() { }

}

The following demonstrates how to use the base() function when there is one parameter in the

constructor.

public class Animal // superclass

{

public Animal(int x) { }

}

public class Cat : Animal // subclass

{

public Cat(int x) : base(x) { }

}

and, when there is more than one parameter in the constructor.

public class Animal // superclass

{

public Animal(int x, int y) { }

}

public class Cat : Animal // subclass

{

Page 6: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 278

public Cat(int x, int y) : base(x, y) { }

}

In the following example, “Student” is a subclass of “Person”. The constructor of “Student”

must use the base() function to inherit the constructor of “Person”.

using System;

using System.Windows.Forms;

public class Person

{

public Person(char gender) // superclass constructor

{

String msg;

switch (gender)

{

case 'F' : msg = "woman"; break;

case 'M' : msg = "man"; break;

default : msg = "No such gender"; break;

}

MessageBox.Show(msg);

}

}

public class Student : Person

{

public Student(char gender) : base(gender) { }

public static void Main()

{

Student obj1 = new Student('F');

}

}

Inheritance

enhances code

reusability

Inheritance strongly supports the concept of reusability. Once a class is written and tested, it can

be inherited by as many subclasses as possible to suit their requirements. The entire .Net

Framework, for example, provide a large number of classes for programmers to use.

In the following figure, the “Shape” class is a superclass and can be specialized to three

subclasses: “Square”, “Rectangle”, and “Rhombus”.

The following is the sample code of the “Shape” class which contains three public instance

variables w, h, and cortex as well as one public method area(). There is a constructor that takes

two parameters, _w and _h of double type. If this constructor is used, the passed value of _w

and _h will be assigned to w and h.

public class Shape

{

public int cortex = 4;

public double w, h;

public Shape() { } //default constructor

Shape

Square Rectangle Rhombus

Page 7: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 279

public Shape(double _w, double _h) //constructor

{

w = _w;

h = _h;

}

public void area()

{

MessageBox.Show("Area: " + w*h);

}

}

With “inheritance”, both “Square” and “Rectangle” classes can immediately inherit all the

public members defined in “Shape”. However, it is necessary for the subclass to have an

appropriate re-declaration of the public constructors.

public class Square : Shape

{

public Square() : base() { } //empty default constructor

// empty constructor

public Square(double _w, double _h) : base(_w, _h) { }

}

public class Rectangle : Shape

{

public Rectangle() : base() { }

public Rectangle(double _w, double _h) : base(_w, _h) { }

}

The following demonstrates how to create instances of “Square” and “Rectangles” classes and use the inheritance to access members of the “Shape” class. In this example, codes of the

“Shape” class are reused by two subclasses.

public class Example

{

public static void Main()

{

Square s1 = new Square();

s1.w = 6.5;

s1.h = 6.5;

s1.area();

Rectangle r1 = new Rectangle(4.3, 7.6);

r1.area();

}

}

A subclass can override any public member of the superclass including instance variables and

methods. In the following example, both w and h variables of the “Shape” superclass are

overridden by “Rectangle” subclass using the new keyword. By the way, the overriding changes

the data type of w and h to int in the “Rectangle” class.

using System;

using System.Windows.Forms;

public class Shape

{

public int cortex = 4;

Page 8: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 280

public double w, h;

public Shape(double _w, double _h) { w = _w; h = _h; }

}

public class Rectangle : Shape

{

new int w; // overriding w

new int h; // overriding h

public Rectangle(int _w, int _h) : base( _w, _h)

{

w = _w; h = _h;

}

}

public class Example

{

public static void Main()

{

Rectangle r1 = new Rectangle(3, 4); // legal

//Rectangle r2 = new Rectangle(3.5, 4.7); // illegal

}

}

Composition The concept of composition in object-oriented program is to combine two or more classes into

one composite class. In other words, composition enables programmers to create a new class to

contain object instances of other classes to fulfill a “Has-A” relationship such as a person has

the ability to work and learn.

As shown in the following figure, a “Smartphone” has three main features: “Phone”, “Camera”,

and “GPS”. The concept of “composition” can be expressed as “a smartphone has functions of

phone, camera, and GPS”. In other words, “a smartphone is a composite of phone, camera, and

GPS”.

In C#, each of the three features can be expressed as an individual class, as shown below.

public class Phone { }

public class Camera { }

public class GPS { }

The following demonstrates how to create a composite class named “Smartphone” which

contains an instance of the three component classes. Consequently, an instance of the

“Smartphone” class contains an instance of “Phone”, “Camera”, and “GPS” classes.

public class Smartphone // composition

{

public Phone p = new Phone();

public Camera c = new Camera();

public GPS g = new GPS();

Smartphone

Phone

Camera

GPS

Page 9: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 281

}

The following demonstrates how to create an instance of “Smartphone” class in an external

class named “Example”. By the way, the “GetType()” method can obtain the class name of a

given instance. The format to identify a particular component (e.g. “p”) class of a composite

class (e.g. “s1”) is compositeInstanceID.componentInstanceID (e.g. “s1.p”).

public class Example

{

public static void Main()

{

Smartphone s1 = new Smartphone();

MessageBox.Show(s1.GetType() + "\n" +

s1.p.GetType() + "\n" +

s1.c.GetType() + "\n" +

s1.g.GetType() + "\n");

}

}

In the following figure, the concept of “composition” can be implemented by creating a

“composite” class named “Person” which contains instances of the “Company” and “School”

classes.

Both “Company” and “School” classes are said to be the “component” classes. Each of the

“component” classes is a fully functional class. Some or all of them members apply to the

“composite” class; therefore, the “composite” class includes instance of the “component”

classes in its code blocks.

The following lists the sample code of “Company” and “School” classes. Each contains three

instance variable and one method.

public class Company

{

public string companyName;

public string jobTitle;

public bool IsEmployeed = true;

public void report() { }

}

public class School

{

public bool IsFinanced;

public bool IsStudent = true;

public double tuition;

public void report() { }

}

Among the members of the “Company” class, only the “IsEmployeed” variable is useful to the

“Person” class. Among the members of the “Company” class, only the “IsStudent” variable is

useful to the “Person” class. The following code illustrates how the “Person” class contains an

instance of the “Company” class and an instance of the “School” classes in order to use only the

“IsEmployeed” variable and the “IsStudent” variable.

public class Person

{

............

public Person(string fn, string ln, bool work, bool learn)

Person

Company

(work) School

(learn)

Page 10: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 282

{

Company c1 = new Company();

School s1 = new School();

if (work != true) { c1.IsEmployeed = false; }

if (learn != true) { s1.IsStudent = false; }

...........

}

}

Polymorphism Polymorphism is a biology term that literally means “multiple forms”. It describes the

phenomena that two or more different phenotypes often exist in the same population of a species. In terms of object-oriented programming, ‘polymorphism” is the ability for the same

code to be used with several different types of objects and for the code to behave differently

depending on the actual type of object used.

In C#, polymorphism can be implemented by two different ways: overloading and overriding.

It is necessary to understand the difference between method overloading and method

overriding.

Operation Description

overloading Creating multiple methods in a class with the same name but different

parameters and types is called method overloading.

overriding Creating the method in a derived class with the same name, the same

parameters and the same return type as in a base class is called method overriding.

In a given class, when multiple methods have the same name but are different in behaviors

(forms), these methods are overloaded methods. For example, the following class contains two

methods. However, both methods have exactly the same identifier “add”. One accepts only int

type; the other accepts only double type. The overloading happens inside the same class.

using System;

using System.Windows.Forms;

public class Example

{

int add(int x, int y) // original form

{

return (x + y);

}

double add(double x, double y) //form2

{

return (x + y);

}

public static void Main(String[] args)

{

Example obj = new Example();

String str = obj.add(3, 5) + "\n";

str += obj.add(9.2, 4.5) + "\n";

MessageBox.Show(str);

}

}

Page 11: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 283

More than two forms of methods can coexist in a given class. In the following example, the

“Example” class contains five implementations of the “showIt()” method.

public class Example

{

public string str;

public Example()

{

str = "";

}

public void showIt(int x) // form 1

{

str += "int type: " + x + "\n";

}

public int showIt(int x, int y) // form 2

{

return (x * y);

}

public void showIt(double x, double y) // form 3

{

str += "Tow double types: " + (x / y) + "\n";

}

public void showIt(char x) // form 4

{

str += "char type: " + x + "\n";

}

public void showIt(string x) // form 5

{

str += "String type: " + x + "\n";

}

}

After instantiating an object of the “Example” class, the C# runtime will use the so-called “late-

binding” technique to decide which of the many forms of a given method should be used. For

functions, “binding” means to match the call with the right function definition by the compiler.

Late binding refers to function calls that are not resolved until run time. In other words, the

“binding” is done when the compiler processes the function call. In the following example, the

compiler will determine which of the five forms of “showIt()” function to use. public class Excercise

{

public static void Main()

{

Example e1 = new Example();

e1.showIt(5); // form 1

e1.showIt(3, 7); // form 2

e1.showIt(17.9, 6.4); // form 3

e1.showIt('A'); // form 4

e1.showIt("Hello!"); // form 5

}

}

While overloading can happen in exactly the same class, overriding can happen between a

subclass and its superclass. The following adds a “ChildExample” as subclass of the “Exercise”

class. The instructor purposely overrides the showIt() method in the “ChildExample” class.

Page 12: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 284

public class ChildExample : Example // subclass

{

public void showIt(double x) // form 6

{

str += "double type: " + x*x + "\n";

}

}

The following code can demonstrate how the overriding works between a subclass and its

superclass.

class Excercise

{

public static void Main()

{

.........

ChildExample c1 = new ChildExample ();

c1.showIt(7); // no overriding

c1.showIt(7.1); // overriding

}

}

The following is a class named “Coffee” with a “brew()” method in it. The “brew()” method

takes one parameter named “flavor” of string type.

public class Coffee

{

public string str;

public Coffee() { str = ""; }

public void brew(string flavor) // original form

{

str += "The taste is " + flavor + ".\n";

}

}

The following defines the “FrenchVanilla” class as a subclass to “Coffee” so that it can inherit

members from the “Coffee” class. However, this FrenchVanilla class overrides the “brew()”

method. The overridden “brew()” method does not require the parameter.

public class FrenchVanilla : Coffee

{

public void brew() // second form

{

str += "The taste is French Vanilla.\n";

}

}

The instantiation of a FrenschVanilla object (e.g. “cup2”) can use the overridden forms of

“brew()” method as illustrated in the following example.

class MyCoffee

{

public static void Main()

{

FrenchVanilla cup2 = new FrenchVanilla();

cup2.brew(); // using 2nd form

cup2.brew("Nest"); // using original form

MessageBox.Show(cup2.str);

}

Page 13: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 285

}

By the same token, the instructor creates another subclass named “Latte” with another form of

“brew()” method in it, as shown below. This form of “brew()” method requires a char type of

parameter. Inside the “brew()” method, there is an if..else..if statement to evaluate the

expression and respond accordingly.

public class Latte : Coffee

{

public void brew(char option) // third form

{

str += "The taste is ";

if (option=='B') { str += "Blue mountain.\n"; }

else if (option=='M') { str += "Mocca.\n"; }

else if (option=='U') { str += "Japanese UCC.\n"; }

else { str += "Unknown taste.\n"; }

}

}

Instances of the “Latte” class can also enjoy two forms of “brew()” method, as illustrated

below.

class Exercise

{

public static void Main()

{

Latte cup3 = new Latte();

cup3.brew('M'); // using 3rd form

cup3.brew("Folgers"); // using original form

MessageBox.Show(cup3.str);

}

}

Practical

Example

Most cars, especially sedans, all come with built-in mechanism for checking statuses of engine,

air conditioning, GPS, and so on. The self-checking mechanism adopts a centralized control

design model. Different sensors are used to check with different systems, parts, or components.

The results of checking are sent to a microprocessor that collects and stores logging data.

The following figure illustrates a sample “self-checking” system which creates: (1) a

“composite” class named “CarStatusLog”, (2) one component class named “Engine”, (3) one

component class named “AirCondition”, (4) one component class named “GPS”.

The concept of “composition” enables the instructor to create the “CarStatusLog” class as a

composite which contains instances of “Engine”, “AirCondition”, and “GPS” classes. Similar to

the situation in which a power switch on the wall can turn four connected lights on or off, each

time when an instance of the “CarStatusLog” class is created, an instance of “Engine”,

“AirCondition”, and “GPS” classes will be created, too.

In this coding project, “Engine”, “AirCondition”, and “GPS” classes represents three different

sensors. Their codes have similar structures. They all have one instance variable of string type

named “status” and are defaulted to “off”.

CarStatusLog

Engine

AirCondition

GPS

Page 14: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 286

public class Engine

{

public string status = "off";

}

public class AirCondition

{

public string status = "off";

}

public class GPS

{

public string status = "off";

}

The “CarStatusLog” class simulates the centralized control of the “self-checking” system.

Whenever the engine is turned on, the “self-checking” system is immediately activated. The

“self-checking” system then initiates a communication with sensors engine, air-conditioning,

and GPS system to check their status. In the code, creating an instance of the “Engine” class

simulates the initiation of communication with the engine sensor. If the “engine” is on, the

“status” variable of the “Engine” class is assigned a value “on”; otherwise, it stays as “off”.

public class CarStatusLog // composition

{

public string status = "";

public CarStatusLog(bool ac, bool gps)

{

Engine e1 = new Engine();

e1.status = "on"; // checking when only engine is on

AirCondition a1 = new AirCondition(); //check AC

if (ac == true) { a1.status = "on"; }

GPS g1 = new GPS(); //check GPS

if (gps == true) { g1.status = "on"; }

status += "Engine: " + e1.status + " ";

status += "AC: " + a1.status + " ";

status += "GPS: " + g1.status + "\n";

}

}

It is necessary to note that the instructor assumes that the “self-checking” system can only be

activated after the engine is turned on. Therefore, if the “self-checking” system is activated, the

engine should have already been turned on.

The following sample code and figure illustrates how the entire “self-checking” system is

installed in a “rental car”. Declaring an instance of the “CarStatusLog” class inside the

“RentalCar” class simulates the installation of the “self-checking” system in a rental car.

public class RentalCar

{

static CarStatusLog c1;

...

}

The following demonstrates how four car-initiation events are logged.

RentalCar CarStatusLog

Page 15: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 287

public class RentalCar

{

static CarStatusLog c1;

static string log = "SELF CHECKING LOG\n";

public static void Main()

{

c1 = new CarStatusLog(true, true);

log += c1.status;

c1 = new CarStatusLog(false, true);

log += c1.status;

c1 = new CarStatusLog(true, false);

log += c1.status;

c1 = new CarStatusLog(false, false);

log += c1.status;

MessageBox.Show(log);

}

}

Review

Questions

1. According to the following code segment, which is an invalid instantiation?

public class Cat : Animal { }

A. Cat c1 = new Cat();

B. Animal c1 = new Animal();

C. Animal c1 = new Cat(); D. Cat c1 = new Animal();

2. Given the following code segment, which is the base class?

public class B : A { ... }

A. A

B. B C. A and B

D. not specified

3. Which declare an object called child to represent the Derived construct?

A. Derived() child;

B. Derived child : base;

C. Derived child = new Derived();

D. child = new Derived();

4. Which associates the show() method to an object called apple?

A. apple.show();

B. apple::show(); C. apple += show();

D. apple -> show();

5. Which statement is correct?

A. A derived class inherits everything from the base class except constructors and destructors.

B. The public members of the Base class become the public members of the Derived class also.

C. Even the private members of the base class are inherited to the derived class, even though

derived class can't access them.

D. All of the above

Page 16: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 288

6. Which is the correct way for a subclass (named "Apple") to inherit the default constructor

from a superclass (named "Fruit") in C#?

A. public Apple() : base() { }

B. public Apple() : Fruit() { } C. public Apple() { base(); }

D. public Fruit.Apple() { }

7. Given the following code, which statement is correct?

public class B : A { public B() { } }

A. B is the base class. A is the derived class. B. A is the base class. B is the derived class.

C. B is the base class. A is the superclass.

D. A is the derived class. B is the subclass.

8. Given the following code, which can override w by changing its type to "int" in a subclass in

C#?

public class Shape {

public double w, h;

}

A. int w;

B. int new w;

C. new int w;

D. (int) w;

9. Given the following code, which can override the default constructor "myAdd()"?

public class myAdd {

public myAdd() { }

}

A. public myAdd(String str) { }

B. public myAdd(int i) { }

C. public myAdd(double x, double y) { }

D. All of the above.

10. Which is the wrong way to override the add() method of the following code?

public class myAdd {

void add(String s) { }

}

A. int add(int x) { return x; }

B. double add(double x) { return x; }

C. char add(char c) { return c; }

D. void add(String s) { return s; }

Page 17: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 289

Lab #9 Inheritance and Polymorphism

Learning Activity #1: Inheritance

1. Create a new directory called C:\CIS218 if it does not exist.

2. Launch the Developer Command Prompt.

3. In the prompt, type cd c:\cis218 and press [Enter] to change to the C:\CIS218 directory.

4. In the prompt, type notepad lab9_1.cs and press [Enter] to use Notepad to create a new source file called

lab9_1.cs with the following contents:

using System;

using System.Windows.Forms;

public class Shape // base class

{

public int cortex = 4;

public double w, h;

public Shape() { }

public Shape(double _w, double _h)

{

w = _w;

h = _h;

}

public string area()

{

return "Area: " + (w *h );

}

public string showType()

{

return (this.GetType() + ""); // obtain the class name

}

}

public class Square : Shape // derived class

{

public Square() : base() { }

public Square(double _w, double _h) : base(_w, _h) { } // empty constructor

}

public class Rectangle : Shape // derived class

{

public Rectangle() : base() { }

public Rectangle(double _w, double _h) : base(_w, _h) { }

}

public class Example

{

public static void Main()

{

string str = "";

Page 18: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 290

Square s1 = new Square();

s1.w = 6.5;

s1.h = 6.5;

str += "Class: " + s1.showType() + "\n";

str += "Cortex: " + s1.cortex + "\n";

str += s1.area() + "\n\n";

Square s2 = new Square(7.4, 7.4);

str += "Class: " + s2.showType() + "\n";

str += "Cortex: " + s2.cortex + "\n";

str += s2.area() + "\n\n";

Rectangle r1 = new Rectangle();

r1.w = 15.9;

r1.h = 9.2;

str += "Class: " + r1.showType() + "\n";

str += "Cortex: " + r1.cortex + "\n";

str += r1.area() + "\n\n";

Rectangle r2 = new Rectangle(4.3, 7.6);

str += "Class: " + r2.showType() + "\n";

str += "Cortex: " + r2.cortex + "\n";

str += r2.area() + "\n\n";

MessageBox.Show(str);

}

}

5. Compile and test the program. A sample output looks:

6. Download the “assignment template”, and rename it to lab9.doc if necessary. Capture a screen shot similar to

the above and paste it to the Word document named lab9.doc (or .docx).

Learning Activity #2: demonstration of inheritance

1. Under the C:\cis218 directory, use Notepad to create a new source file called lab9_2.cs with the following

contents:

using System;

using System.Windows.Forms;

public class Point // superclass

{

public double x;

public double y;

public double z;

public Point() // default constructor, set to (0, 0)

{

x = 0;

y = 0;

Page 19: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 291

z = 0;

}

public Point(double _x, double _y)

{

x = _x;

y = _y;

z = 0;

}

public double Distance()

{

return Math.Sqrt(x*x + y*y) + z*z;

}

}

public class Point3D : Point// subclass

{

public Point3D() : base() { } //inheritance

public Point3D(double _x, double _y, double _z) : base(_x, _y) //inheritenace

{

z = _z; // overriding

}

}

public class Example

{

public static void Main()

{

string str = "";

Point3D p3D1 = new Point3D();

str += "point: (" + p3D1.x + ", " + p3D1.y + ", " + p3D1.z + ")\n";

str += "Distance to origin: " + p3D1.Distance() + "\n\n";

Point3D p3D2 = new Point3D();

p3D2.x = 15.6;

p3D2.y = 97.4;

p3D2.z = 101.3;

str += "point: (" + p3D2.x + ", " + p3D2.y + ", " + p3D2.z + ")\n";

str += "Distance to origin: " + p3D2.Distance() + "\n\n";

Point3D p3D3 = new Point3D(98, 97, 96);

str += "point: (" + p3D3.x + ", " + p3D3.y + ", " + p3D3.z + ")\n";

str += "Distance to origin: " + p3D3.Distance() + "\n\n";

MessageBox.Show(str);

}

}

2. Compile and test the program. A sample output looks:

3. Capture a screen shot similar to the above and paste it to the Word document named lab9.doc (or .docx).

Page 20: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 292

Learning Activity #3: Composition

1. Under the C:\cis218 directory, use Notepad to create a new source file called lab9_3.cs with the following

contents: using System;

using System.Windows.Forms;

public class Engine // component class

{

public string status = "off";

}

public class AirCondition // component class

{

public string status = "off";

}

public class GPS // component class

{

public string status = "off";

}

public class CarStatusLog // composition

{

public string status = "";

public CarStatusLog(bool ac, bool gps)

{

Engine e1 = new Engine();

e1.status = "on"; // self-checking is actived when only engine is on

AirCondition a1 = new AirCondition(); //check AC

if (ac == true) { a1.status = "on"; }

GPS g1 = new GPS(); //check GPS

if (gps == true) { g1.status = "on"; }

status += "Engine: " + e1.status + " ";

status += "AC: " + a1.status + " ";

status += "GPS: " + g1.status + "\n";

}

}

public class MyCar

{

public static void Main()

{

string log = "SELF CHECKING LOG\n";

CarStatusLog c1 = new CarStatusLog(true, true);

log += c1.status;

CarStatusLog c2 = new CarStatusLog(false, true);

log += c2.status;

CarStatusLog c3 = new CarStatusLog(true, false);

log += c3.status;

CarStatusLog c4 = new CarStatusLog(false, false);

log += c4.status;

MessageBox.Show(log);

Page 21: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 293

}

}

2. Compile and test the program. A sample output looks:

3. Capture a screen shot similar to the above and paste it to the Word document named lab9.doc (or .docx).

Learning Activity #4: Composition

1. Under the C:\cis218 directory, use Notepad to create a new source file called lab9_4.cs with the following

contents:

using System;

using System.Windows.Forms;

public class Company // component class

{

public string companyName;

public string jobTitle;

public bool IsEmployeed = true; // used by composite class

public void report() { }

}

public class School // component class

{

public bool IsFinanced;

public bool IsStudent = true; // used by composite class

public double tuition;

public void report() { }

}

public class Person // composite class

{

public string status;

public Person(string fn, string ln, bool work, bool learn)

{

Company c1 = new Company();

School s1 = new School();

if (work != true) { c1.IsEmployeed = false; }

if (learn != true) { s1.IsStudent = false; }

status = fn + "\t" + ln + "\t";

status += c1.IsEmployeed + "\t";

status += s1.IsStudent;

}

public static void Main()

{

Person p1 = new Person("Jennifer", "Lopez", true, true);

Page 22: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 294

Person p2 = new Person("Nicole", "Kidman", true, false);

Person p3 = new Person("Demi", "Moore", false, true);

Person p4 = new Person("Jodie", "Foster", false, false);

MessageBox.Show(p1.status + "\n" +

p2.status + "\n" +

p3.status + "\n" +

p4.status + "\n");

}

}

2. Compile and test the program. A sample output looks:

3. Capture a screen shot similar to the above and paste it to the Word document named lab9.doc (or .docx).

Learning Activity #5: Polymorphism

1. Under the C:\cis218 directory, use Notepad to create a new source file called lab9_5.cs with the following

contents:

using System;

using System.Windows.Forms;

public class Coffee

{

public string str;

public Coffee() { str = ""; }

public void brew(string flavor) // original form

{

str += "The taste is " + flavor + ".\n";

}

public string showType()

{

return (this.GetType() + ""); // obtain the class name

}

}

public class FrenchVanilla : Coffee

{

public void brew() // second form

{

str += "The taste is French Vanilla.\n";

}

}

public class Latte : Coffee

{

public void brew(char option) // third form

{

Page 23: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 295

str += "The taste is ";

if (option=='B') { str += "Blue mountain.\n"; }

else if (option=='M') { str += "Mocca.\n"; }

else if (option=='U') { str += "Japanese UCC.\n"; }

else { str += "Unknown taste.\n"; }

}

}

class MyCoffee

{

public static void Main()

{

Coffee cup1 = new Coffee();

cup1.brew("Maxwell Roast"); // using original form

FrenchVanilla cup2 = new FrenchVanilla();

cup2.brew(); // using 2nd form

cup2.brew("Nest"); // using original form

Latte cup3 = new Latte();

cup3.brew('M'); // using 3rd form

cup3.brew("Folgers"); // using original form

MessageBox.Show(cup1.showType() + "\n" + cup1.str + "\n" +

cup2.showType() + "\n" + cup2.str + "\n" +

cup3.showType() + "\n" + cup3.str);

}

}

2. Compile and test the program. A sample output looks:

3. Capture a screen shot similar to the above and paste it to the Word document named lab9.doc (or .docx).

Submittal

1. Complete all the 5 learning activities.

2. Create a .zip file named lab9.zip containing ONLY the following self-executable files.

• Lab9_1.exe

• Lab9_2.exe

• Lab9_3.exe

• Lab9_4.exe

• Lab9_5.exe

• Lab9.doc (or .docx) [You may be given zero point if this Word document is missing]

3. Log in to course site and enter the course site.

4. Upload the zipped file as response to question 11.

Page 24: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 296

Programming Exercise:

1. Use Notepad to create a new file named ex09.cs with the following heading lines (be sure to replace

YourFullNameHere with the correct one):

//File Name: ex09.cs

//Programmer: YourFullNameHere

2. Under the above two heading lines, write C# codes to create a superclass (or base class) and a subclass (or

derived class) based on the following specifications:

Superclass (Parent, Base)

Class Name Computer

Class Members • One public variable of string type named “model”

• One public variable of double type named “unitPrice”

• One public variable of int type named “qty”

• One public constructor that takes three parameters named “m”, “p”, and “q’.

They will pass values to “model”, “unitPrice”, and “qty” inside the

constructor’s code block.

Subclass (Child, Derived)

Class Name Laptop

Class Member • One public but empty constructor that takes three parameters named “m”, “p”,

and “q’. This constructor must inherits the constructor from “Computer” class.

• One public void function named “printIt()” that (1) uses the GetType() method

[Hint: this.GetType()] to obtain and the class name, (2) obtains of values

assigned to “model”, “unitPrice”, and “qty” variables, (3) display all the

obtained value in a message box.

3. Make sure the “Laptop” subclass will inherit all public member from the “Computer” superclass.

4. In the “Laptop” subclass, create a Main() method. In the Main() method, create an instance named “lap1” of the

“laptop” class. Assign the following values of the fields of “computer” class.

Variable Name Value

model “ASUS101”

unitPrice 375.99

qty 12

5. The following is a sample output.

6. Download the “programming exercise template”, and rename it to ex09.doc. Capture a screen shot similar to the

above figure and then paste it to the Word document named “ex09.doc” (or .docx).

Page 25: inheritance superclass base parent subclass derived childstudents.cypresscollege.edu/cis218/lc09.pdfVisual C# - Penn P. Wu, PhD. 276 In the above code, the “inheritance” allows

Visual C# - Penn P. Wu, PhD. 297

7. Compress the source code (ex09.cs), the executable (ex09.exe), and the Word document (ex09.doc or .docx) to

a .zip file named “ex09.zip”. You may be given zero point if any of the required file is missing.

Grading Criteria:

• You must be the sole author of the codes.

• You must meet all the requirements in order to earn credits. You will receive zero if you simply display the

message.

• No partial credit is given.