slide1 n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Section 5 – Classes PowerPoint Presentation
Download Presentation
Section 5 – Classes

Loading in 2 Seconds...

play fullscreen
1 / 46

Section 5 – Classes - PowerPoint PPT Presentation


  • 92 Views
  • Uploaded on

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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Section 5 – Classes' - khan


Download Now An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
slide2

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
slide3

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 problem
  • Operations implement object behaviour
slide4

Classes

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

}

}

slide5

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.

slide6

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.

slide7

C# - Basics: Classes

  • Declaration
    • public Class MyClass{...}
  • Constructors
    • publicMyClass(parameters) {...}
  • newoperator – create an instance of the class
    • MyClassobjMyClass = newMyClass();
slide8

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

}

}

slide9

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
slide10

Class Definition and Members

  • Class definition consists of
    • Class declaration
    • Data Fields
    • Constructors
    • Properties
    • Methods
slide11

Contents of Classes

class class_name{

... data fields, constants...

... methods...

... constructors...

... properties...

... derived classes...

}

slide12

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.
slide13

Calling the constructor

ClassNameobjectName = new ClassName(argumentList);

Or

ClassNameobjectName;

objectName = new ClassName(argumentList);

slide14

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)

{

this.name = name;

this.age = age;

}

// More code ...

}

As rule constructors should initialize all class fields.

slide15

using System;

class OutputClass

{

private string myString;

// Constructor

public OutputClass(string inputString)

{

myString = inputString;

}

public void printString()

{

Console.WriteLine(myString);

}

}

Continued …

slide16

// Program start class

class ExampleClass

{

// Main begins program execution.

public static void Main()

{

// Instance of OutputClass

OutputClassoutCl = new OutputClass("This is printed by the output class.");

// Call OutputClass method

outCl.printString();

}

}

slide17

To create an instance (i.e. object) of a class, use the new operator which invokes the class constructor.

newclass_name(parameters)

Variables of type class_name can be created in this way:

class_nameobject_name = newclass_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).

slide18

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!

slide19

Accessor and Mutator Examples

publicdoubleGetNoOfSquareMeters( )

{

returnnoOfSquareMeters;

}

publicvoidSetNoOfSquareMeters(doublesquareMeters)

{

noOfSquareMeters = squareMeters;

}

Accessor

Mutator

slide20

Property

  • 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
slide21

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
slide22

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 validation
slide23

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 ...
  • }
slide24

class MyClass

{

private string message ;

public string Message

{

get

{

return message;

}

set

{

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);

Console.ReadLine();

}

}

slide25

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
  • {
  • get
      • {
      • return width * height;
      • }
  • }
  • }
slide26

How to Use Classes

  • Create an instance
    • Initialize its fields
  • Manipulate the instance
    • Read / modify properties
    • Invoke methods
slide27

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
slide28

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
slide29

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;

}

slide30

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);

}

}

slide31

Example

  • 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
slide32

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)
  • {
  • dog.Bark();
  • }
  • }
  • }
slide33

Inheritance

  • 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 behavior.

The derived class may override inherited attributes and behaviour

slide35

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

{

...

}

slide36

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 class
      • - The base class constructor willexecute first
  • Any derived class inherits all the data and methods of its base class
    • - Including private data and methods
    • - Cannot use or modify private data and methods directly
slide37

using System;

public class ParentClass

{

public ParentClass()

{

Console.WriteLine("Parent Constructor.");

}

public void print()

{

Console.WriteLine("I'm a Parent Class.");

}

}

public class ChildClass : ParentClass

{

public ChildClass()

{

Console.WriteLine("Child Constructor.");

}

public static void Main()

{

ChildClass child = new ChildClass();

child.print();

}

}

Child class object invokes print() inherited from

parent class.

slide38

Creating Base Classes for Inheritance

  • Can define your own classes from which other classes can inherit
  • 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
slide39

Overriding Base Class Methods

  • Derived class contains data and methods defined in the original class
  • Polymorphism
    • Using the same method or property name to indicate different implementations
  • Derived class can override and hide methods and data from the base class
slide40

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 greeting.

Then a derived Dog class is defined - the Dog class inherits from the Animal class.

slide41

Animal myAnimal= new Animal();

myAnimal.Greet();

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.

slide42

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 virtual.

slide43

If you want to, you can still access the inherited method, even when you override it, using the base keyword.

public override void Greet()

{

base.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#.

slide44

Accessing Base Class Methods from a Derived Class

  • Use the keyword base to access the parent class method
slide45

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
slide46

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