OOP Class5

esse quam videri
Revision as of 19:41, 19 February 2006 by Jeff (talk | contribs)
Jump to: navigation, search

Class Relationship

Operator Overloading

<csharp>public static ClassType operator + ( object lhs, object rhs ) {

   ClassType c
   //code to implement class addition
   return c;

}</csharp>

Operator also refer to implicit and explicit conversions. Fractions make a good example for opertor overloading. Fraction class

   * Create fractions from two numbers x/y or from whole numbers
   * Convert fractions to wholenumbers int
   * Convert fractions to float or double
   * OverRide ToString to decribe Fraction


Fraction Class Example of operator overloading. /infod/jeff/classSource/class5/fractionConv.cs - source Fraction class with implicit and explicit conversion /infod/jeff/classSource/class5/fractionConv_NoTest.cs - source Fraction class with overridden operators /infod/jeff/classSource/class5/fractionConvOver.cs - source

In class build a test application does thigs with frations. Using /infod/jeff/classSource/class5/fractionDone_NoTest.cs create a test class or web page that...

   * Creates a fraction out of integers (ie cast int into fractions)
   * Adds, subtracts, and reduces some fractions
   * Creates floting point numbers out of fractions (is cast fraction into double)
   * Checks the eqaulity of some fractions


More objects

Shared Members - static members

aka Shared Properties

Static - A type of member modifier that indicates that the member applies to the type rather than an instance of the type

<csharp>public class Dog { //some code

static private int dogCount; // total number of dogs

public Dog() { barkSound = "Woof!!!"; //Add a dog to the total dog count dogCount++; } public Dog(string newName) { name = newName; barkSound = "Woof!!!"; //Add a dog to the total dog count dogCount++; }</csharp>

Static dougCount Example /infod/jeff/classSource/class5/dogStatic.cs-source

Class Relationships

Four Class Relation ships

  • Association - 'Uses A'
  • Containment - 'Has A'
  • Inheritance - 'Is A'
  • Interfaces - implements or derives from


Association - 'Uses A'

A dog uses a hydrant to relieve them self.

<csharp>//Dog simple class definition public class Dog {

   //some dog code...
   
   public void Relieve(Hydrant h)
   {
    h.Clean = false;
   }

}

public class Hydrant {

 public string Color; //the color of the hydrant
 public bool Clean;   //if the hydrant is clean or dirty
 
 public Hydrant()
 {
   Color = "red";
   Clean = true;
 }
 
 public override string ToString ()
 {
   if (this.Clean == true)
   {
    return ("The " + this.Color + " hydrant is clean.");
   }
   else
   {
    return ("The " + this.Color + " hydrant is not clean.");
   }
 }

}</csharp>

Dog Association example /infod/jeff/classSource/class5/DogHydrant.cs -source

Containment - 'Has A'

A dog has an owner

Dog fido = new Dog("fido"); fido.Owner = new Person("Sue");

<csharp>//Dog simple class definition public class Dog {

   public string Name;        // the dog's name
   public string BarkSound;    // the sound of the dog's bark
   public Person Owner;    // the dogs owner
   
   public Dog(string dogName)
   {
       Name = dogName;
       BarkSound = "Woof!!!";
   }
   public string Bark() { 
       string s;
       s = this.Name + " says " + this.BarkSound;
       //Make sure the the dog has an owner
       if (!(this.Owner == null))
          s += "\n" + Owner.Name + " says be quiet.";
       return s;
   }

}

public class Person

 {
   public string Name;      //the color of the hydrant
   
   public Person(string newName)
   {
     Name = newName;
   }
 }</csharp>


Containment example /infod/jeff/classSource/class5/DogOwner.cs -source

Inheritance - 'Is A'

C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from.

A Basenji is an African barkless dog. A Basenji is a dog. syntax

<csharp>public class Basenji : Dog {

   //override constructor
   public Basenji() : base()
   {
       barkSound = "Basenjis don't bark, but they do howl and growl.";
       dogCount++;
   }
   public override void Bark()
   {
       Console.WriteLine("Basenjis dont bark.");
   }

// some more code.... }

public class Dog { // some dog code... //methods need to be marked virtual or protected to be overridden

   public virtual void Bark() 
   { 
       //make dog bark
       Console.WriteLine (this.Name + " says " + this.barkSound);
       //add 1 to the number of times the dog has barked
       this.barkCount++ ;
   }

}</csharp>

Basenji.cs -source

Virtual Functions - A class modifier that indicates that a method can be overridden by a derived class.

Abstract Classes abstract - A class modifier that specifies that the class must be derived from to be instantiated.

<csharp>abstract public class Mammal { private string birth; private string skin;

public Mammal() { birth = " gives birth to live young."; skin = " has Hair."; }

public string Birth { get { return birth; } } public string Skin { get { return skin; } } }</csharp>

Inheritance example /infod/jeff/classSource/class5/DogMammal.cs -source

Polymorphic Types - Different types implementing the same functionality. webopedia polymorphism The C# Station Tutorial - Lesson 9: Polymorphism

<csharp>abstract public class Mammal { private string name; private string birth; private string skin;

public Mammal() { name = "none"; birth = " gives birth to live young."; skin = " has Hair."; }

public Mammal(string newName) { name = newName; birth = " gives birth to live young."; skin = " has Hair."; }

public string Birth { get { return birth; } } public string Skin { get { return skin; } } public string Name { get { return name; } set { name = value; } } public virtual void Bark() { Console.WriteLine("Some Mammals Bark."); } }

public class Dog : Mammal { public string BarkSound; // the sound of the dog's bark

public Dog(string newName) { Name = newName; BarkSound = "Woof!!!"; }

public override void Bark() { base.Bark(); Console.WriteLine(this.Name + " says " + this.BarkSound); } public void Eat() { //put eat code here } }

public class Basenji : Dog { //override constructor public Basenji(string newName) : base(newName) { BarkSound = "basenjis don't bark, but they do howl and growl."; }

public override void Bark() { base.Bark(); Console.WriteLine("\nBasenjis dont bark."); }

   // some more code....

}</csharp>

/infod/jeff/classSource/class5/DogPoly.cs -source Structs - remember these from week 2

Lightweight alternatives to classes. Structs do not support inheritance or destructors. Structs are value typed objects similar to ints bool etc... while classes are refence types. Structs are more memory efficient and and faster than classes. Syntax

[ attributes] [access-modifiers] struct identifier [:interface-list {struct members}

<csharp>struct Dog {

public string name;
public string weight;
public int age;

}</csharp>

Interfaces - implements or derives from

An interface is a class that lacks implementation. The only thing it contains are definitions of events, indexers, methods and/or properties. The reason interfaces only provide definitions is because they are inherited by classes and structs, which must provide an implementation for each interface member defined. Since classes in c# can only be derived from one other class ( in c++ it is possible to derive from many) interfaces are used for multiple inheritance. Like abstract classes you cannot create an instance of an interface on derive from it.

/infod/jeff/classSource/class5/interface.cs -source /infod/jeff/classSource/class5/interface2.cs -source Phone interface example phoneIFace.cs -source Multiple interface inheritance - inherits IPhone, Cell, POTS /infod/jeff/classSource/class5/phoneIFacePOTS.cs -source

Using Built in objects Namespaces - Maps set of types to a common name.

Namespaces are used to help organzize types into logical groups. IMporting namespaces allows you to refer to the directly rather than typeing the full path.

namespace identifier {...}

Example of Namespaces and nested namespaces /infod/jeff/classSource/class5/Namespace.cs -source

C:\backup\csharp>csc Namespace.cs
Microsoft (R) Visual C# .NET Compiler version 7.10.3052.4
for Microsoft (R) .NET Framework version 1.1.4322
Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.


C:\backup\csharp>Namespace.exe
First Example of calling another namespace member.
Second Example of calling a nested namespace member.
Third Example of calling another namespace member.

C:\backup\csharp>

Name spaces can also be set to other namespaces. This is known as aliasing an can be usefull to avoid namespace confilcts or save typeing on long namespaces.
/infod/jeff/classSource/class5/AliasNamespace.cs -source

C:\backup\csharp>csc AliasNamespace.cs
Microsoft (R) Visual C# .NET Compiler version 7.10.3052.4
for Microsoft (R) .NET Framework version 1.1.4322
Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.


C:\backup\csharp>AliasNamespace.exe
This is a member of csharp_station.tutorial.myExample.
Not a member of csharp_station.tutorial.myExample.

C:\backup\csharp>

HomeWork

Make a class that subclasses you previous class
Make a class the uses your previous class

Links

The C# Station Tutorial - Lesson 7: Introduction to Classes The C# Station Tutorial - Lesson 7: Lesson 8: Class Inheritance The C# Station Tutorial - Lesson 9: Polymorphism The C# Station Tutorial - Lesson 10: Properties The C# Station Tutorial - Lesson 12: Structs The C# Station Tutorial - Lesson 13: Interfaces C# Fundamentals - tutorial 4