Difference between revisions of "OOP Class5"

esse quam videri
Jump to: navigation, search
(Properties Private instance data members - accessors)
(This keyword)
Line 56: Line 56:
 
</csharp>
 
</csharp>
  
==This keyword==
 
 
The this keyword used within a class refers to the current instance of the class
 
 
<csharp>public Time( int CurrentYear, int CurrentDay)
 
{
 
this.Year = CurrentYear;
 
this.Day = CurrentDay;
 
}</csharp>
 
  
 
Here's a class of dogs that return differnt color depending on whether on not they are clean. It uses private private instance data memebrs and the this keyword
 
Here's a class of dogs that return differnt color depending on whether on not they are clean. It uses private private instance data memebrs and the this keyword
Line 207: Line 198:
  
 
an example of how you don't need to know how all of the classes work just how to use them
 
an example of how you don't need to know how all of the classes work just how to use them
 
 
  
 
==In Class Project==
 
==In Class Project==

Revision as of 14:52, 5 October 2006

Properties Private instance data members - accessors

Micorsoft has stared calling private varables with accessors Properties

Private class memebers the use get and set keyword to set and retrieve data. Get and set are known as accessor methods private members are helpfull when you want to also do other things when a data member is changed or change the rutern value under certian conditions. C# Programmer's Reference - Accessors http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfaccessorspg.asp. Lastly accessor also make read only and write only variables possible

<csharp>//private string color read/write private string color;

public string Color {

 get
 {
  return color;
 }
 set
 {
  color = value;
 }

}

//private string color read only private string color;

public string Color {

 get
 {
  return color;
 }

}</csharp>


Another property that is a good candidate for a private instance data member is the dogs age

<csharp> private string age;

public string Age {

 //age can only be accessed with get there is no set accessor
 //age must be set with HappyBirthday()
 get
 {
  return Age;
 }

}

Public int HappyBirthday() {

 age++;
 return age;

}


</csharp>


Here's a class of dogs that return differnt color depending on whether on not they are clean. It uses private private instance data memebrs and the this keyword

<csharp>//Accessor for private color allow color to be set and return color or 'dirty' + color

   public string Color
   {
       get
       {
           //if current dog isClean the return dogs color
           if (this.isClean == true)
           {
               return color;
           }
           //else return 'dirty' and the dogs color
           else {
               return "dirty " + color;
           }
       }
       set
       {
          color = value;
       }
   }</csharp>

console /infod/jeff/classSource/class4/dogAccessor.cs - source web /infod/jeff/classSource/class4/dogAccessor.aspx - source

Dog private members, Overloaded with method class definition

<csharp>//Dog private members, Overloaded with method class definition public class Dog {

	private string name;		// the dog's name

private int age; // the dog's age private int weight; // the dog's weight private string barkSound; // the sound of the dog's bark private int barkCount; // how many times the dog has barked

public Dog() { barkSound = "Woof!!!"; } public Dog(string newName) { name = newName; barkSound = "Woof!!!"; } public Dog(string newName, string newBarkSound ) { name = newName; barkSound = newBarkSound; }

public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { age = value; } } public int Weight { get { return weight; } set { weight = value; } } public string BarkSound { get { return barkSound; } set { barkSound = value; } } public int BarkCount //you can't set bark count //it only increments from the Bark() method { get { return barkCount; } }

   public string About() 

{ //return a string with some information about the dog

       string about = "";

//this refers to current object about +=("\nThe dogs name is " + this.name + "."); about +=("\nIt is " + this.age + " years old."); about +=("\nIt weighs " + this.weight + " lb(s)."); about +=("\nIts bark sounds like '" + this.barkSound + "'"); about +=("\nIt has barked " + this.barkCount + " time(s)" );

       about += about.Replace("\n","

");

       return about;

}

public 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++ ; } public void Eat() { //put eat code here } }</csharp>

console

dogOverloadMethodScoped.cs


Real barking dogs...

DogBark

an example of how you don't need to know how all of the classes work just how to use them

In Class Project

In class build traingle class. Properties

  • sideA
  • sideB
  • sideC

Methods

  • Area //A method that reurn the area of the triangle
     use Heronian formula which is able to compute the area of a triange by knowing the length of the three sides.
     triangle area given a,b,c = sqrt(s(s-a)(s-b)(s-c)) when s = (a+b+c)/2 (Heron's formula)

<csharp>// Heronian formula double s = (a + b + c) / 2.0; double dArea = Math.Sqrt(s*(s-a)*(s-b)*(s-c)); </csharp>

Once you have built the triangle class build a class to test it. The test class should create a triangle with

sideA= 3
sideB= 4
sideC= 5

and then display the area as text in the console.

http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/tri_class.cs tri_class.cs]

Class Relationship

Look a classes from homework.

Discuss TV and Radio class

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
dogStatic.cs - source

Class Relationships

Four Class Relation ships

  • Association - 'Uses A'
  • Containment - 'Has A'
  • Inheritance - 'Is A'
  • Interfaces - implements or derives from We'll do this next week in OOP Class6

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 DogHydrant.cs - source

Containment - 'Has A'

A dog has an owner


<csharp>Dog fido = new Dog("fido"); fido.Owner = new Person("Sue");</csharp>

<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
DogOwner.cs -source

Inheritance - 'Is A'

ArsDigita University Course 04: Object-oriented Program Design and Software Engineering - Lecture Notes 3

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. We will look at virtual function when we look at abstract classes

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

Polymorphism (computer science) Different types implementing the same functionality.
polymorphism webopedia 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>

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>

This is a pretty lightweight dog and is pretty useless as a dog (It's can't even bark what fun is that) so I won't make an example.

A good example of a stuct would be and something like a point. There may be many many points in a structure or graph and we would want the points to be a lightweight as possible. Since the point object won't have an methods this is a good time to use a struct.

<csharp>struct Point {

   public int x;
   public int y;
   public Point(int x, int y)
   {
       this.x = x;
       this.y = y;
   }
   public Point Add(Point pt)
   {
       Point newPt;
       newPt.x = x + pt.x;
       newPt.y = y + pt.y;
       return newPt;
   }

}</csharp>

Operator Overloading

You can overload operator in c# just like you overload constuctors

   * Operator Overloading In C# - www.csharphelp.com
   * Operator Overloading in C# - HowToDoThings.com

<csharp>//Overloading unary operators public static return_type operator op (Type t) {

 	// Statements

}

//Overloading binary operators public static ClassType operator + ( object lhs, object rhs ) {

	ClassType c

//code to implement class addition return c; }</csharp>

dog addition? extra credit

How could you overload + operator so that it returns a new dog when two dogs are added together...


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.
fractionConv.cs - source
Fraction class with implicit and explicit conversion
fractionConv_NoTest.cs - source
Fraction class with overridden operators
fractionConvOver.cs - source

In class build a test application does thigs with frations.
Using

http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/fractionConv_NoTest.cs fractionDone_NoTest.cs] create a test class 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

HomeWork

READ

  1. Chapter 9 Inside Methods p 111-123
  2. Chapter 11 Inheritance and Polymorphism p 134-154
  3. Chpater 12 Operator Overloading p 155 - 172
  4. chapter 13 Structs p 172 - 177 (relax its only 54 pages total)

DO

Extend the class that you worked on last week.
Demonstrate Inhertance 'Is A' with your class.

  • Make a class the subclasses or superclasses your previous class.

Demonstrate

  • Containment 'Has A'
    • Make a class that contains or is contained by your old class
  • Association - 'Uses A'
    • Make a class that uses your original class

Thy to build a class that superclass you old tv and radio classes. Use inheritance to simplify your implementaion.


Quiz 2 next week

Links

The C# Station Tutorial - Lesson 7: Introduction to Classes
The C# Station Tutorial - 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
The C# Station Tutorial - Lesson 4: C# Fundamentals