0% found this document useful (0 votes)
5 views5 pages

C# Classes, Inheritance, and Polymorphism Guide

Uploaded by

hungnhth2209065
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

C# Classes, Inheritance, and Polymorphism Guide

Uploaded by

hungnhth2209065
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PROGRAMMING IN C#

Module 6: Classes and Methods


Module 7: Inheritance and Polymorphism
Lab Guide for Lab3

Session Objectives
In this session, you will be practicing with
 Classes and Methods
 Inheritance and Polymorphism

Part 1 – Getting started (30 minutes)


1. Creating class, object, invoking fields and methods of object

Following an application has two class Car and Program.


Class Car has 4 fields:
 string make
 string model
 string color
 int yearBuilt
and 2 methods:
 void Start(): just prints its informations and string “Start”.
 void Stop():just prints its informations and string “Start”.
Class Program in Main method creates some its objects and use its fields and methods.

Scan the code first, type the code, compile, run and observe the result.
1. Create class Car
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()
{
[Link](model + " started");
}
public void Stop()
{
[Link](model + " stopped");
}
}
2. Create class Program
class Program
{
public static void Main()
{
// declare a Car object reference named myCar
Car myCar;
// create a Car object, and assign its address to myCar
[Link]("Creating a Car object and assigning "
+ "its memory location to myCar");
myCar = new Car();

// assign values to the Car object's fields using myCar


[Link] = "Toyota";
[Link] = "MR2";
[Link] = "black";
[Link] = 1995;

// display the field values using myCar


[Link]("myCar details:");
[Link]("[Link] = "+ [Link]);
[Link]("[Link]= "+[Link]);
[Link]("[Link] = "+[Link]);
[Link]("[Link]=" +[Link]);

// call the methods using myCar


[Link]();
[Link]();

// declare another Car object reference and


// create another Car object
[Link]("Creating another Car object
and"+"assigning its memory location to redPorsche");
Car redPorsche = new Car();
[Link] = "Porsche";
[Link] = "Boxster";
[Link] = "red";
[Link] = 2000;
[Link]("redPorsche is a " + [Link]);
//change the object referenced by the myCar object //reference
to the object referenced by redPorshe
[Link]("Assigning redPorsche to myCar");
myCar = redPorsche;
[Link]("myCar details:");
[Link]("[Link] = " + [Link]);
[Link]("[Link] = " +[Link]);
[Link]("[Link] = " +[Link]);
[Link]("[Link] = "+[Link]);
// assign null to myCar (myCar will no longer reference
//an object)
myCar = null;
[Link]();
}
}

2. Create subclass and using override method.

This application create 3 class: Window, ListBox, Button and Polimorphism. ListBox and Button are
subclasses of Window. Class Window has method DrawWindow and its two subclases override it. Class
Polimorphism will create some their objects and use its methods to test the polimorphism.

1. Create class Window


class Window
{
// constructor takes two integers to
// fix location on the console
public Window(int top, int left)
{
[Link] = top;
[Link] = left;
}
// simulates drawing the window
public virtual void DrawWindow()
{
[Link]("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;
}

2. Create class ListBox


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()
{
[Link](); // invoke the base method
[Link]("Writing string to the listbox:{0}",
listBoxContents);
}
private string listBoxContents; // new member variable
}

3. Create class Button


class Button : Window
{
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()
{
[Link]("Drawing a button at {0}, {1}\n", top,left);
}
}

4. Create class Polimorphism


class Polymorphism
{
public 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);
[Link]();
[Link]();
[Link]();
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();
}
[Link]();
}
}

Part 2 – Do it your self

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 * percentage where
percentage is given as parameter)

Write a Test program to test all the behaviors of above Employee class

Common questions

Powered by AI

Creating the 'Car' and 'Program' classes demonstrates basic object-oriented programming principles such as encapsulation and class instantiation. The 'Car' class encapsulates data in the form of fields (make, model, color, yearBuilt) and behaviors in methods (Start, Stop). The 'Program' class illustrates how to instantiate and interact with 'Car' objects, setting field values and invoking methods. This encapsulation allows for modular code organization and reuse of objects throughout the application .

The 'override' keyword in the 'ListBox' and 'Button' classes is used to indicate that these classes are providing a new implementation of the 'DrawWindow' method originally defined in the 'Window' class. This keyword is crucial for polymorphic behavior, as it allows the derived classes to offer specialized functionality while maintaining a common interface defined by the base class. It enhances class functionality by enabling dynamic dispatch, meaning that the version of the method that gets executed is based on the actual object type at runtime rather than the reference type .

The 'Car' class follows a two-step process for object creation: first, a reference variable 'myCar' of type 'Car' is declared but not yet initialized. Then, a new 'Car' object is created using the 'new' keyword, and its memory address is assigned to 'myCar'. This illustrates object references in C#, where 'myCar' refers to the object's memory location, allowing access to the object's fields and methods. Modifications to 'myCar' directly affect the referenced object, showcasing how references point to and modify underlying objects .

Benefits of using a base class reference to an array containing derived class objects include enhanced flexibility and simplified code management, as it allows treating different types of objects through a uniform interface, which is essential for polymorphic behavior. This facilitates extending system capabilities without modifying existing code structure, thereby supporting maintainability. However, limitations include potential performance overhead due to dynamic method invocation at runtime, and the inability to directly access derived class-specific members without explicit type casting or additional methods, restricting some operations purely to those defined in the base class .

Polymorphism in C# is demonstrated through the use of virtual and override keywords. The base class 'Window' declares a virtual method 'DrawWindow', which can be overridden by any derived class. The 'ListBox' and 'Button' classes inherit from 'Window' and override 'DrawWindow' to customize its behavior. This allows objects of these derived classes to be treated as objects of the base class 'Window', enabling dynamic method invocation based on the object's actual type at runtime. When the 'DrawWindow' method is invoked on an array of 'Window' objects containing 'Window', 'ListBox', and 'Button' objects, the overridden methods in 'ListBox' and 'Button' are called, showcasing polymorphism .

The 'Employee' class demonstrates encapsulation by encapsulating employee-related data as private instance variables (firstName, lastName, address, sin, salary). It provides a constructor to initialize these variables, ensuring controlled and consistent object state upon creation. The override of the 'ToString' method presents employee information, showing the importance of customizing behavior for better data representation. Additionally, a method to calculate bonuses encapsulates logic pertinent to employee salary, adhering to the principle of keeping related data and behavior together .

Inheritance enhances code reusability by allowing derived classes like 'ListBox' and 'Button' to inherit common functionality from the base 'Window' class, such as managing the 'top' and 'left' fields and the base implementation of 'DrawWindow'. This eliminates code duplication and leverages existing implementations. It also adds scalability, as new derived classes can be added without altering existing functionality in the base class, facilitating extension and maintenance of the codebase as system requirements grow or change .

Method overriding in derived classes allows polymorphic arrays of the base class to dynamically invoke the overridden methods according to the object's actual runtime type. In the provided example, an array of 'Window' objects contains instances of 'Window', 'ListBox', and 'Button'. When iterating over this array, the 'DrawWindow' method is called for each object. Due to method overriding, the specific version of 'DrawWindow' corresponding to the actual type of each object ('Window', 'ListBox', or 'Button') is executed, demonstrating polymorphism .

The fields 'top' and 'left' in the 'Window' class serve as coordinates for positioning window elements in the console. They are protected fields, meaning they are accessible within derived classes. The derived classes 'ListBox' and 'Button' inherit these fields and utilize them in their overridden 'DrawWindow' methods to customize the output display by printing the top-left coordinates where the elements are drawn .

The 'Polymorphism' class tests polymorphism by creating an array of 'Window' objects that includes 'Window', 'ListBox', and 'Button' objects. It then iterates over this array, calling the 'DrawWindow' method on each element. Due to method overriding, the call to 'DrawWindow' is resolved at runtime based on each object's actual type, demonstrating polymorphic behavior. This setup illustrates how polymorphism enables writing code that is generic and flexible, allowing interaction with objects of different types interchangeably through a common base class interface .

You might also like