Section 5 – Classes
Object-Oriented Language Features
• Abstraction
– Abstract or identify the objects involved in the problem
• Encapsulation
– Packaging data and behaviour into a single unit - the class
• Inheritance
– Reuse of code through extending program units
• Polymorphism
– Multiple implementations of the same behaviour
Classes in C#
• Classes model real-world objects and define
– Attributes (state, properties, fields)
– Behaviour (methods, operations)
• Classes describe the structure of objects
– Objects describe particular instance of a class
• Properties hold information about the modeled object relevant to the
• Operations implement object behaviour
Classes are declared by using the keyword class followed
by the class name and a set of class members surrounded
by curly braces { }.
using System;
public class House
public class Program
public static void Main()
int bedrooms = 3; // assuming bedrooms defined in House
Basic syntax for class declaration
Class comprises a class header and class body.
public class class_name
class body
Note: No semicolon (;) to terminate class block.
But statements must be terminated with a semicolon ;
Class body comprises class members – constructor, data
fields and methods.
In C#, individual classes and class members need to be
prefixed with visibility modifiers.
By default, if you declare a member variable (or anything
else) in a class but do not specify its access level, the
member is considered private and cannot be accessed
from outside, i.e. by a non-member of that class.
Therefore, to make a member accessible by other classes,
you must declare it as public.
You can use a mix of public and private members in a
class and there is no rule on which access level should be
listed first or last.
C# - Basics: Classes
• Declaration
public Class MyClass {...}
• Constructors
public MyClass(parameters) {...}
• new operator – create an instance of the class
MyClass objMyClass = new MyClass();
Variables of a class type are created with the new operator
using System;
public class House
public class Program
public static void Main()
House MyHouse = new House(); // create object
• Classes in C# can have members:
– Data fields, methods, properties, indexers, events, operators,
constructors, destructors, …
– Inner classes
• Members can have access modifiers
– public, private, …
• Members can be
– static (common) or specific for a given object
Class Definition and Members
• Class definition consists of
– Class declaration
– Data Fields
– Constructors
– Properties
– Methods
Contents of Classes
class class_name {
... data fields, constants...
... methods...
... constructors...
... properties...
... derived classes...
Every class has a constructor, which is called automatically any time an
instance of a class is created.
The purpose of constructors is to initialize class members when the class
is created.
Constructors do not have return values and always have the same name
as the class.
Classes can have multiple constructors, as long as the parameter list is
different for each constructor.
The constructor with no parameters is known as the default constructor.
If a class does not define any constructors, an implicit parameterless
constructor is created.
Calling the constructor
ClassName objectName = new ClassName(argumentList);
ClassName objectName;
objectName = new ClassName(argumentList);
public class Person
private string name;
private int age;
// Parameterless constructor
public Person()
name = null;
age = 0;
// Constructor with parameters
public Person(string name, int age)
{ = name;
As rule constructors
this.age = age;
should initialize all class
// More code ...
using System;
class OutputClass
private string myString;
// Constructor
public OutputClass(string inputString)
myString = inputString;
public void printString()
Continued …
// Program start class
class ExampleClass
// Main begins program execution.
public static void Main()
// Instance of OutputClass
OutputClass outCl = new OutputClass("This is printed
by the output class.");
// Call OutputClass method
To create an instance (i.e. object) of a class, use the new
operator which invokes the class constructor.
new class_name(parameters)
Variables of type class_name can be created in this way:
object_name = new class_name(params);
The dot operator (.) is used in conjunction with the object
to access the members (properties and methods) of a class
(like C++ and Java).
Access Modifiers
• Class members can have access modifiers
– Used to restrict the classes (i.e. clients) able to access them
– Supports the OOP principle "encapsulation“
• Class members can be:
– public – accessible from any class
– private – accessible from the class itself only
There are others!
Accessor and Mutator Examples
public double GetNoOfSquareMeters( )
return noOfSquareMeters;
public void SetNoOfSquareMeters(double squareMeters)
noOfSquareMeters = squareMeters;
• A new feature for C# - another way of implementing accessor
and mutator methods.
• Properties look like a data field
– But more closely aligned to methods
• Standard naming convention in C# for properties
– Use the same name as the instance variable or field, but
start with uppercase character
The Role of Properties
• Expose object's data to the outside world
• Control how the data is manipulated
– Ensure the internal object state is correct
– E.g. price should always be kept positive
• Properties can be:
– Read-only
– Write-only
– Read and write
Defining Properties
• Properties work as a pair of methods
– Getter and setter
• Properties should have
– Access modifier (public)
– Return type
– Unique name
– Get and / or Set part
– Can contain code processing data in specific way, e.g. apply
Defining Properties – Example
public class Point
private int xCoord;
private int yCoord;
public int XCoord
get { return xCoord; }
set { xCoord = value; }
public int YCoord
get { return yCoord; }
set { yCoord = value; }
// More code ...
class MyClass
private string message ;
public string Message
return message;
message = value;
class Program
static void Main()
// create instance of MyClass
MyClass greetings = new MyClass();
greetings.Message = "Hello World!";
string answer = greetings.Message;
Console.WriteLine("{0}", answer);
Dynamic Properties
• Properties are not bound to a class field – they can be used calculate
a value dynamically
public class Rectangle
private double width;
private double height;
// More code ...
public double Area
return width * height;
How to Use Classes
1. Create an instance
– Initialize its fields
2. Manipulate the instance
– Read / modify properties
– Invoke methods
Example - Define Class for a Dog
• Define a simple class that represents information about a dog
– The dog should have name and breed
– If there is no name or breed assigned to the dog
• It should be named “Fido"
• Its breed should be “Mongrel"
– It should be able to view and change the name and the breed of
the dog
– The dog should be able to bark
To define a simple class that represents information about a dog
The dog should have name and breed → data fields – string type
If there is no name and breed assigned to the dog
It should be named “Fido"
Its breed should be “Mongrel" → constructors
It should be able to view and change the name and the breed of
the dog → get and set methods
The dog should be able to bark → method
public class Dog
private string name;
private string breed;
public Dog()
// Constructors
name = “Fido";
breed = “Mongrel";
public Dog(string dogName, string dogBreed)
name = dogName;
breed = dogBreed;
public string Name
// get and set properties
get { return name; }
set { name = value; }
public string Breed // get and set properties
get { return breed; }
set { breed = value; }
public void Bark()
Console.WriteLine("{0} said: Woof!", name);
• Task is as follows:
– Create 3 dogs
– Put all dogs in an array
– Iterate through the array elements and ask each dog to bark
– Note:
• Use the Dog class from the previous example
public class Doggies
static void Main()
// Use the Dog constructor to set name and breed
Dog firstDog = new Dog(); // default
Dog secondDog = new Dog(“Fritz”, “German Shepherd”);
Dog thirdDog = new Dog(“Tommy”, “Bulldog”);
// Save the dogs in an array
Dog[] dogs = new Dog[] {firstDog, secondDog, thirdDog };
// Ask each of the dogs to bark
foreach(Dog dog in dogs)
• Enables you to
– Create a general class and then define specialized classes
that have access to the members of the general class
• Associated with an "is a" relationship
– Specialized class “is a” form of the general class
A derived (or child) class inherits from a base (or parent) class
The derived class inherits all the attributes and behaviour of the
base class.
The derived class may implement also its own attributes and
The derived class may override inherited attributes and behaviour
Inheritance hierarchy for Shapes.
Extending Classes
• Use a single colon
– Between the derived class name and its base class name
• Inheritance works only in one direction
– A child inherits from a parent
public class ChildClass : ParentClass
Child class may implement its own constructors, attributes and
methods in addition to those inherited from the parent class.
Instantiating an object of a derived class
- Calls the constructor for both the base class and the derived
- The base class constructor will execute first
Any derived class inherits all the data and methods of its base
- Including private data and methods
- Cannot use or modify private data and methods directly
using System;
public class ParentClass
public ParentClass()
public class ChildClass : ParentClass
public ChildClass()
Console.WriteLine("Child Constructor.");
public static void Main()
ChildClass child = new ChildClass();
public void print()
Console.WriteLine("I'm a Parent Class.");
Child class object invokes print() inherited from
parent class.
Creating Base Classes for Inheritance
• Can define your own classes from which other classes can
• Base class is also called the super or parent class
• Data members are defined with a private access modifier
• Constructors are defined with public access modifiers
• Properties offer public access to data fields
Overriding Base Class Methods
• Derived class contains data and methods defined in the original
• Polymorphism
– Using the same method or property name to indicate different
• Derived class can override and hide methods and data from the
base class
public class Animal
public void Greet()
Console.WriteLine("Hello, I'm some sort of animal!");
public class Dog : Animal
This example defines an Animal class, with a simple method to output a
Then a derived Dog class is defined - the Dog class inherits from the Animal
Animal myAnimal = new Animal();
Dog myDog = new Dog();
myDog.Greet(); // use parent class method
Even though we have not defined a Greet() method for the Dog class, it still
knows how to greet us, because it inherits this method from the Animal class.
May also define a Greet() method in the Dog class … that overrides the one in
the parent class.
public class Animal
public virtual void Greet()
Console.WriteLine("Hello, I'm some sort of animal!");
public class Dog : Animal
public override void Greet()
Console.WriteLine("Hello, I'm a dog!");
Besides the added method on the Dog class, you should notice two things:
I have added the virtual keyword to the method in the Animal class, and on the
method in the Dog class, I use the override keyword.
In C#, you are not allowed to override a member of a class unless it is marked as
If you want to, you can still access the inherited method, even when you override
it, using the base keyword.
public override void Greet()
Console.WriteLine("Yes I am - a dog!");
Inheritance is not only from one class to another - you can have a whole hierarchy
of classes, which inherits from each other.
- For instance, we could create a Puppy class, which inherits from our Dog
class, which in turn inherits from the Animal class.
What you cannot do in C#, is to let one class inherit from several other classes at
the same time.
- Multiple inheritance, as it is called, is not supported by C#.
Accessing Base Class Methods from a Derived Class
• Use the keyword base to access the parent class method
Overriding Methods
• Replace the method defined at a higher level
• Keyword override included in derived class
– Base method includes virtual, abstract, or override keyword
• Overriding differs from overloading a method
– Overridden methods have exactly the same signature
– Overloaded methods each have a different signature
Overriding Methods (continued)
• Example of polymorphism
– ToString( ) method can have many different definitions
– ToString( ) uses the virtual modifier, implying that any class
can override it
• Derived classes inherit from a base class
– Also called subclasses or child classes
• Protected access modifiers
– Access only to classes that derived from them
– Access to change data in the base class
Related flashcards

Classes of computers

19 cards

ARM architecture

23 cards

Web development

38 cards

System software

24 cards

Borland software

18 cards

Create Flashcards