C# - Lab 1 – Class and method, Inheritance and Polymorphism
Programming in C#
Lab 3
Objectives:
At the end of this session, you will able to understand:
Classes and Methods
Inheritance and Polymorphism
Part I: Workshop – 15 minutes
Students open workshop in CD ROM, then View, Run, Think about it.
Part II: Step by step – 45 minutes
Exercise 1: Creating a class
Step 1: Open Visual Studio 2005
Step 2: Select the menu File->New->Project to create console based project named ‘ClassDemo’ and
Solution named Session03 as following
© 2009 FPT Aptech 2
C# - Lab 1 – Class and method, Inheritance and Polymorphism
Step 3: Rename the class file ‘program.cs‘ to ‘ClassDemo.cs’
Step 4: Replace code in ‘ClassDemo.cs’ with given code
using System;
class Car
{
// declare the fields
public string make;
public string model;
public string color;
public int yearBuilt;
// define the methods
public void Start()
{
System.Console.WriteLine(model + " started");
}
public void Stop()
{
System.Console.WriteLine(model + " stopped");
}
}
class ClassDemo
{
public static void Main()
{
// declare a Car object reference named myCar
Car myCar;
// create a Car object, and assign its address to myCar
System.Console.WriteLine("Creating a Car object and assigning " +
"its memory location to myCar");
myCar = new Car();
// assign values to the Car object's fields using myCar
myCar.make = "Toyota";
myCar.model = "MR2";
myCar.color = "black";
myCar.yearBuilt = 1995;
// display the field values using myCar
System.Console.WriteLine("myCar details:");
System.Console.WriteLine("myCar.make = " + myCar.make);
System.Console.WriteLine("myCar.model = " + myCar.model);
System.Console.WriteLine("myCar.color = " + myCar.color);
System.Console.WriteLine("myCar.yearBuilt = " + myCar.yearBuilt);
// call the methods using myCar
myCar.Start();
myCar.Stop();
// declare another Car object reference and
// create another Car object
System.Console.WriteLine("Creating another Car object and " +
"assigning its memory location to redPorsche");
Car redPorsche = new Car();
redPorsche.make = "Porsche";
redPorsche.model = "Boxster";
© 2009 FPT Aptech 3
C# - Lab 1 – Class and method, Inheritance and Polymorphism
redPorsche.color = "red";
redPorsche.yearBuilt = 2000;
System.Console.WriteLine("redPorsche is a " + redPorsche.model);
// change the object referenced by the myCar object reference
// to the object referenced by redPorshe
System.Console.WriteLine("Assigning redPorsche to myCar");
myCar = redPorsche;
System.Console.WriteLine("myCar details:");
System.Console.WriteLine("myCar.make = " + myCar.make);
System.Console.WriteLine("myCar.model = " + myCar.model);
System.Console.WriteLine("myCar.color = " + myCar.color);
System.Console.WriteLine("myCar.yearBuilt = " + myCar.yearBuilt);
// assign null to myCar (myCar will no longer reference an
object)
myCar = null;
Console.ReadLine();
}
}
Step 5: Select menu File -> Save to save the file
Step 6: Select Build -> Build ClassDemo option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of the program as following
Exercise 2: Nested Class
Step 1: Add a console based project ‘NestedClass’ to the solution
Step 2: Right click on project NestedClass -> set as Startup project
Step 3: Rename the class file ‘Program.cs’ to ‘NestedClass.cs’
Step 4: Replace the code in ‘NestedClass.cs’ with the given code
using System;
class Car
© 2009 FPT Aptech 4
C# - Lab 1 – Class and method, Inheritance and Polymorphism
{
// declare the Engine class
public class Engine
{
// declare the Engine fields
public int cylinders;
public int horsepower;
// define the Engine method
public void Start()
{
System.Console.WriteLine("Engine started");
}
// declare the Car fields
public string make;
public Engine engine; // Car has an Engine
// define the Car method
public void Start()
{
engine.Start();
}
}
class ClassDemo2
{
public static void Main()
{
// declare a Car object reference named myCar
System.Console.WriteLine("Creating a Car object");
Car myCar = new Car();
myCar.make = "Toyota";
// Car objects have an Engine object
System.Console.WriteLine("Creating an Engine object");
myCar.engine = new Car.Engine();
myCar.engine.cylinders = 4;
myCar.engine.horsepower = 180;
// display the values for the Car and Engine object fields
System.Console.WriteLine("myCar.make = " + myCar.make);
System.Console.WriteLine("myCar.engine.cylinders = " +
myCar.engine.cylinders);
System.Console.WriteLine("myCar.engine.horsepower = " +
myCar.engine.horsepower);
// call the Car object's Start() method
myCar.Start();
Console.ReadLine();
}
}
© 2009 FPT Aptech 5
C# - Lab 1 – Class and method, Inheritance and Polymorphism
Step 5: Select menu File -> Save to save the file
Step 6: Select Build -> Build ‘NestedClass’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following
Exercise 3: Static member
Step 1: Add a console based project ‘StaticMember’ to the solution
Step 2: Right click on project StaticMember -> set as Startup project
Step 3: Rename the class file ‘Program.cs’ to ‘StaticMember.cs’
Step 4: Replace the code in ‘StaticMember.cs’ with the given code
using System;
// declare a Cat class
class Cat
{
// a private static member to keep
// track of how many Cat objects have
// been created
private static int instances = 0;
private int weight;
private String name;
// cat constructor
// increments the count of Cats
public Cat(String name, int weight)
{
instances++;
this.name = name;
this.weight = weight;
}
// Static method to retrieve
// the current number of Cats
public static void HowManyCats()
{
Console.WriteLine("{0} cats adopted",
instances);
}
public void TellWeight()
{
Console.WriteLine("{0} is {1} pounds",
© 2009 FPT Aptech 6
C# - Lab 1 – Class and method, Inheritance and Polymorphism
name, weight);
}
}
class ClassDemo3
{
public void Run()
{
Cat.HowManyCats();
Cat frisky = new Cat("Frisky", 5);
frisky.TellWeight();
Cat.HowManyCats();
Cat whiskers = new Cat("Whisky", 7);
whiskers.TellWeight();
Cat.HowManyCats();
}
public static void Main()
{
ClassDemo3 t = new ClassDemo3();
t.Run();
Console.ReadLine();
}
}
Step 5: Select menu File -> Save to save the file
Step 6: Select Build -> Build ‘StaticMember’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following
Exercise 3: Using “virtual” and “override” keyword
Step 1: Add a console based project ‘OverrideMethod’ to the solution
Step 2: Right click on project Polymorphism -> set as Startup project
Step 3: Rename the class file ‘Program.cs’ to ‘OverrideMethod.cs’
Step 4: Replace the code in ‘OverrideMethod.cs’ with the given code
using System;
public class B
{
© 2009 FPT Aptech 7
C# - Lab 1 – Class and method, Inheritance and Polymorphism
public virtual void Display()
{
Console.WriteLine("Class B's Display Method");
}
}
public class C : B
{
public override void Display()
{
Console.WriteLine("Class C's Display Method");
}
}
public class ContainedClass
{
int MyInt = 0;
}
public class D : C
{
public ContainedClass MyClass = new ContainedClass();
public override void Display()
{
Console.WriteLine("Class D's Display Method");
}
}
class ClassDemo1
{
static void Main(string[] args)
{
B MyB = new D();
D MyD = new D();
//Both result in in D's instance of Display being //called
MyB.Display();
MyD.Display();
Console.ReadLine();
}
}
Step 5: Select menu File -> Save to save the file
Step 6: Select Build -> Build ‘OverrideMethod’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following
© 2009 FPT Aptech 8
C# - Lab 1 – Class and method, Inheritance and Polymorphism
Exercise 4: Polymorphism
Step 1: Add a console based project ‘Polymorphism’ to the solution
Step 2: Right click on project Polymorphism -> set as Startup project
Step 3: Rename the class file ‘Program.cs’ to ‘Polymorphism.cs’
Step 4: Replace the code in ‘Polymorphism.cs’ with the given code
using System;
class Window
{
// constructor takes two integers to
// fix location on the console
public Window(int top, int left)
{
this.top = top;
this.left = left;
}
// simulates drawing the window
public virtual void DrawWindow()
{
Console.WriteLine("Window: drawing Window at {0}, {1}",
top, left);
}
// these members are protected and thus visible
// to derived class methods. We'll examine this
// later in the chapter
protected int top;
protected int left;
}
// ListBox derives from Window
class ListBox : Window
{
// constructor adds a parameter
public ListBox(int top,
int left,string contents):base(top, left) // call base
constructor
{
listBoxContents = contents;
}
// an overridden version (note keyword) because in the
// derived method we change the behavior
public override void DrawWindow()
{
base.DrawWindow(); // invoke the base method
Console.WriteLine("Writing string to the listbox: {0}",
listBoxContents);
}
private string listBoxContents; // new member variable
}
class Button : Window
{
© 2009 FPT Aptech 9
C# - Lab 1 – Class and method, Inheritance and Polymorphism
public Button(int top, int left): base(top, left)
{
}
// an overridden version (note keyword) because in the
// derived method we change the behavior
public override void DrawWindow()
{
Console.WriteLine("Drawing a button at {0}, {1}\n",top, left);
}
}
class Polymorphism
{
static void Main(string[] args)
{
Window win = new Window(1, 2);
ListBox lb = new ListBox(3, 4, "Stand alone list box");
Button b = new Button(5, 6);
win.DrawWindow();
lb.DrawWindow();
b.DrawWindow();
Window[] winArray = new Window[3];
winArray[0] = new Window(1, 2);
winArray[1] = new ListBox(3, 4, "List box in array");
winArray[2] = new Button(5, 6);
for (int i = 0; i < 3; i++)
{
winArray[i].DrawWindow();
}
Console.ReadLine();
}
}
Step 5: Select menu File -> Save to save the file
Step 6: Select Build -> Build ‘OverrideMethod’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following
© 2009 FPT Aptech 10
C# - Lab 1 – Class and method, Inheritance and Polymorphism
Part III: Do it yourself – 60 minutes
Exercise 1:
Design and code a class named Atom that holds information about a single atom. Place your class
definition in a file named Atom.cs. Include the following member functions in your design:
• boolean accept() - prompts for and accepts from standard input
- an integer holding the atomic number,
- a string holding the atomic symbol,
- a string holding the full name of the atom and
- a floating-point value holding the atomic weight.
If any input is invalid, your function rejects that input and requests fresh data.
• void display() - displays the atomic information on standard output.
Design and code a main program that accepts information for up to 10 atomic elements and displays the
atomic information in tabular format.
The program output might look something like:
Atomic Information
==================
Enter atomic number : 3
Enter symbol : Li
Enter full name : lithium
Enter atomic weight : 6.941
Enter atomic number : 20
Enter symbol : Ca
Enter full name : calcium
Enter atomic weight : 40.078
Enter atomic number : 30
Enter symbol : Zn
Enter full name : zinc
Enter atomic weight : 65.409
Enter atomic number : 0
No Sym Name Weight
------------------------------------
3 Li lithium 6.941
20 Ca calcium 40.078
30 Zn zinc 65.409
© 2009 FPT Aptech 11
C# - Lab 1 – Class and method, Inheritance and Polymorphism
Exercise 2:
Write an Employee class to record the following attributes and behaviors for an Employee
• Declare the following instance variables
o string firstName
o string lastName
o string address
o long sin;
o double salary
• Implement a constructor to initialize all the member variables from given
parameters
• Override the ToString method to print the employee info in a good presentable
format
• Define a method to calculate the bonus ( salary x percentage where
percentage is given as parameter)
Write a Test program to test all the behaviors of above Employee class
Part IV: Homework
Exercise 1: Do assignment of module 6 in CD ROM
Exercise 2: Do assignment of module 7 in CD ROM
References
1) CD ROM C# Programming, Aptech Education
2) http://www.java2s.com/Tutorial/CSharp/CatalogCSharp.htm
3) MSDN Document
© 2009 FPT Aptech 12