Difference between revisions of "OOP Class6"

esse quam videri
Jump to: navigation, search
 
(41 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Category:OOP]]
+
[[Category:IAM Classes]]
==access-modifiers==
 
public +
 
:most permissive access. No restrictions on access
 
private -
 
:least permissive access level. Only available to the class in which it was declared
 
protected #
 
:accessible within its class and by derived classes
 
internal
 
:accessible only within files in the same assembly
 
protected internal
 
:combination of protected and internal
 
Public Dog
 
[[Image:DogSimpleUML.png]]
 
  
Dog with private age
+
==Review==
[[Image:DogsimpleAgePrivate.png]]
+
;Accessibility: restrict the visibility of a class and it's members
 +
;Classes: Abstraction that has properties and methods. properties and the ''nouns'' and methods are the ''verbs''Classes are used to define objects.
 +
;Objects: Instance of a class
 +
;Abstraction : Factor out details to work on fewer concepts at a time
 +
;Encapsulation: Allows us to use objects with out completely understanding how everything inside the object works. Encapsulation also allows the internal state of objects to be changed easily without affecting other objects or interfaces. Real barking dogs...[http://iam.colum.edu/oop/browser/browser.aspx?f=/classsource/class4/DogBark DogBark] an example of how you don't need to know how all of the classes work just how to use them
 +
;Polymorphism: many forms that have the same attributes and abilities
 +
;UML : Unified Modeling Language.
  
==Properties Private instance data members - accessors==
+
TODO
Micorsoft has stared calling private varables with accessors Properties
+
;Virtual Functions: Functions that can be overridden.
 +
;Static: Members that are associayed with a class not an instance of the class
  
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
+
==Shared Members - static members==
 +
aka Shared Properties
  
<csharp>//private string color read/write
+
Static - A type of member modifier that indicates that the member applies to the type rather than an instance of the type
private string color;
 
  
public string Color
+
<syntaxhighlight lang="csharp">public class Dog
 
{
 
{
  get
+
//some code
  {
+
 
  return color;
+
static private int dogCount; // total number of dogs
  }
+
 
  set
+
public Dog()
  {
+
{
  color = value;
+
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++;
 +
}</syntaxhighlight>
 +
}
 +
 
 +
Static dougCount Example <br />
 +
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/dogStatic.cs dogStatic.cs] - source
 +
 
 +
 
 +
 
 +
 
 +
 
 +
==OverLoading==
 +
 
 +
You can overload a method to make it more flexible.
 +
 
 +
Simple Bark Method
 +
 
 +
<syntaxhighlight lang="csharp">
 +
public class Dog
 +
{
 +
public string Name; // the dog's name
 +
 +
public string BarkSound; // the sound of the dog's bark
 +
 +
public Dog()
 +
{
 +
BarkSound = "Woof!!!";
 +
}
 +
 +
public string Bark() {
 +
string strBark = this.BarkSound;
 +
                barkCount ++;
 +
                return strBark;
 +
}
 +
   
 +
public void Eat() {
 +
//put eat code here
 +
}
 +
}
 +
</syntaxhighlight>
 +
 
 +
overloaded method that makes a dog bark more than once.
 +
 
 +
<syntaxhighlight lang="csharp">
 +
public class Dog
 +
{
 +
public string Name; // the dog's name
 +
 +
public string BarkSound; // the sound of the dog's bark
 +
 +
public Dog()
 +
{
 +
BarkSound = "Woof!!!";
 +
}
 +
 +
public string Bark() {
 +
string strBark = this.BarkSound;
 +
                barkCount ++;
 +
                return strBark;
 +
}
 +
   
 +
public string Bark(int numBarks) {
 +
string strBark = "";
 +
                for(int i =0; i < numBarks; i++)  //bark many times
 +
                {
 +
                  strBark += this.BarkSound;
 +
                  barkCount ++;
 +
                }
 +
                return strBark;
 +
}
 
}
 
}
 +
</syntaxhighlight>
 +
 +
You can overload a method as much as you want as long as each overload has a '''unique argument signature'''
  
//private string color read only
 
private string color;
 
  
public string Color
+
==Overload Constructor==
 +
 
 +
Overloading the constructor of you class can make it easier to use.
 +
 
 +
here is a simple dog contructor
 +
 
 +
<syntaxhighlight lang="csharp">
 +
public class Dog
 
{
 
{
  get
+
  {
+
public string BarkSound; // the sound of the dog's bark
  return color;
+
  }
+
public Dog()
}</csharp>
+
{
 +
BarkSound = "Woof!!!";
 +
}
 +
 +
}
 +
</syntaxhighlight>
 +
 
 +
we can modify this so that we can pass in the sound of the dogs bark when the object is created
  
 +
<syntaxhighlight lang="csharp">
 +
public class Dog
 +
{
 +
 +
public string BarkSound; // the sound of the dog's bark
 +
 +
public Dog(string newBarkSound)
 +
{
 +
this.BarkSound = newBarkSound;
 +
}
 +
 +
}
 +
</syntaxhighlight>
  
Another property that is a good candidate for a private instance data member is the dogs age
+
or the name of the dog and the barksound
  
<csharp>
 
private string age;
 
  
public int Age
+
<syntaxhighlight lang="csharp">
 +
public class Dog
 
{
 
{
  //age can only be accessed with get there is no set accessor
+
  //age must be set with HappyBirthday()
+
public string BarkSound; // the sound of the dog's bark
  get
+
        public string Name;
  {
+
  return age;
+
public Dog(string newBarkSound, string NewName)
  }
+
{
 +
this.BarkSound = newBarkSound;
 +
                this.Name = newName;
 +
 
 +
}
 +
 
}
 
}
 +
</syntaxhighlight>
 +
 +
you can have as many overoads as you want as long as each overload has a unique '''argument signature'''
 +
 +
<!--
 +
 +
==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
  
public int HappyBirthday()
+
<syntaxhighlight lang="csharp">//Overloading unary operators
 +
public static return_type operator op (Type t)
 
{
 
{
  age++;
+
  // Statements
  return age;
 
 
}
 
}
  
 +
//Overloading binary operators
 +
public static ClassType operator + ( object lhs, object rhs )
 +
{
 +
ClassType c
 +
//code to implement class addition
 +
return c;
 +
}</syntaxhighlight>
 +
 +
dog addition? extra credit
 +
 +
How could you overload + operator so that it returns a new dog when two dogs are added together...
  
</csharp>
 
  
===In class===
 
  
==In Class Project==
 
  
*Build a Dog class with a private variable called age.
 
*Make a public Accessor for the private age the is read only
 
*Make a method that increments the age of your dog
 
*MAke a test class for the new property and accessor
 
  
<!--In class build traingle class.
+
===Operator Overloading Fraction Class===
Properties
+
 
 +
<syntaxhighlight lang="csharp">public static ClassType operator + ( object lhs, object rhs )
 +
{
 +
    ClassType c
 +
    //code to implement class addition
 +
    return c;
 +
}</syntaxhighlight>
 +
 
 +
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 whole numbers int
 +
    * Convert fractions to float or double
 +
    * override ToString() to describe Fraction
 +
 
 +
 
 +
Fraction Class Example of operator overloading.<br />
 +
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/fractionConv.cs fractionConv.cs] - source<br />
 +
Fraction class with implicit and explicit conversion<br />
 +
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/fractionConv_NoTest.cs fractionConv_NoTest.cs] - source<br />
 +
Fraction class with overridden operators<br />
 +
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/fractionConvOver.cs fractionConvOver.cs] - source<br />
 +
 
 +
In class build a test application does thigs with frations.<br />
 +
Using <br />
 +
 
 +
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
 +
 
 +
==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.
 +
 
 +
<syntaxhighlight lang="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.");
 +
    }
 +
  }
 +
}</syntaxhighlight>
 +
 
 +
Dog Association example
 +
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/DogHydrant.cs DogHydrant.cs] - source
 +
 
 +
==Containment - 'Has A'==
 +
A dog has an owner
  
* sideA
 
* sideB
 
* sideC
 
  
Methods
+
<syntaxhighlight lang="csharp">Dog fido = new Dog("fido");
 +
fido.Owner = new Person("Sue");</syntaxhighlight>
  
* Area //A method that reurn the area of the triangle
+
<syntaxhighlight lang="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!!!";
 +
    }
  
      use Heronian formula which is able to compute the area of a triange by knowing the length of the three sides.
+
    public string Bark() {
      triangle area given a,b,c = sqrt(s(s-a)(s-b)(s-c)) when s = (a+b+c)/2 (Heron's formula)
+
        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;
 +
    }
 +
}   
  
<csharp>// Heronian formula
+
public class Person
double s = (a + b + c) / 2.0;
+
  {
double dArea = Math.Sqrt(s*(s-a)*(s-b)*(s-c));
+
    public string Name;      //the color of the hydrant
</csharp>
+
   
 +
    public Person(string newName)
 +
    {
 +
      Name = newName;
 +
    }
 +
  }</syntaxhighlight>
  
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.
+
Containment example<br>
 +
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/DogOwner.cs DogOwner.cs] -source
  
http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/tri_class.cs tri_class.cs]
 
-->
 
  
  
  
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
+
and the this keyword
  
<csharp>//Accessor for private color allow color to be set and return color or 'dirty' + color
+
<syntaxhighlight lang="csharp">//Accessor for private color allow color to be set and return color or 'dirty' + color
 
     public string Color
 
     public string Color
 
     {
 
     {
Line 135: Line 354:
 
           color = value;
 
           color = value;
 
         }
 
         }
     }</csharp>
+
     }</syntaxhighlight>
  
 
console /infod/jeff/classSource/class4/dogAccessor.cs - source
 
console /infod/jeff/classSource/class4/dogAccessor.cs - source
Line 142: Line 361:
 
Dog private members, Overloaded with method class definition
 
Dog private members, Overloaded with method class definition
  
<csharp>//Dog private members, Overloaded  with method class definition
+
<syntaxhighlight lang="csharp">//Dog private members, Overloaded  with method class definition
 
public class Dog
 
public class Dog
 
{
 
{
Line 243: Line 462:
 
//put eat code here  
 
//put eat code here  
 
}
 
}
}</csharp>
+
}</syntaxhighlight>
  
 
console
 
console
Line 249: Line 468:
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dogOverloadMethodScoped.cs dogOverloadMethodScoped.cs]
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dogOverloadMethodScoped.cs dogOverloadMethodScoped.cs]
  
 +
==In class==
  
Real barking dogs...
+
Discuss Dog Diagram
  
[http://iam.colum.edu/oop/browser/browser.aspx?f=/classsource/class4/DogBark DogBark]
+
[[OOP Full Dog Diagram]]
  
an example of how you don't need to know how all of the classes work just how to use them
+
-->
 
 
 
 
 
 
 
 
 
 
==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 <br />
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/dogStatic.cs dogStatic.cs] - source
 
 
 
 
 
==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 Fraction Class===
 
  
<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.<br />
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/fractionConv.cs fractionConv.cs] - source<br />
 
Fraction class with implicit and explicit conversion<br />
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/fractionConv_NoTest.cs fractionConv_NoTest.cs] - source<br />
 
Fraction class with overridden operators<br />
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/fractionConvOver.cs fractionConvOver.cs] - source<br />
 
 
In class build a test application does thigs with frations.<br />
 
Using <br />
 
 
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
 
 
==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'==
 
==Association - 'Uses A'==
Line 361: Line 484:
 
A dog uses a hydrant to relieve them self.
 
A dog uses a hydrant to relieve them self.
  
<csharp>//Dog simple class definition
+
<syntaxhighlight lang="csharp">//Dog simple class definition
 
public class Dog
 
public class Dog
 
{
 
{
Line 394: Line 517:
 
     }
 
     }
 
   }
 
   }
}</csharp>
+
}</syntaxhighlight>
  
 
Dog Association example
 
Dog Association example
Line 403: Line 526:
  
  
<csharp>Dog fido = new Dog("fido");
+
<syntaxhighlight lang="csharp">Dog fido = new Dog("fido");
fido.Owner = new Person("Sue");</csharp>
+
fido.Owner = new Person("Sue");</syntaxhighlight>
  
<csharp>//Dog simple class definition
+
<syntaxhighlight lang="csharp">//Dog simple class definition
 
public class Dog
 
public class Dog
 
{
 
{
Line 437: Line 560:
 
       Name = newName;
 
       Name = newName;
 
     }
 
     }
   }</csharp>
+
   }</syntaxhighlight>
  
  
Line 443: Line 566:
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/DogOwner.cs DogOwner.cs] -source
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/DogOwner.cs DogOwner.cs] -source
  
 +
==Homework==
  
 +
<!--
  
==Structs==
+
use Pair Programming to make tests and classes from the following UML
- 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.
+
[[OOP Students Classes Diagram]]
Syntax
 
  
[ attributes] [access-modifiers] struct identifier
+
If you need to ad any supprting methods or properties that are not on the diagram feel free.
[:interface-list {struct members}
 
  
<csharp>struct Dog
+
Create a UML Diagram of your c# classes (not the tv and radio yeah the pong machine and ninja and kungfumonkey and stuff)
{
+
-->
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.
+
Chapter 2 Introduction the UML in The Unified Modeling Language Users Guided (hand out)
  
<csharp>struct Point
+
Chapter 4 Classes in The Unified Modeling Language Users Guided (hand out)
{
+
-->
    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>
 
 
 
==In class==
 
 
 
Discuss Dog Diagram
 
 
 
[[OOP Full Dog Diagram]]
 
 
 
==Pair Programming==
 
 
 
[http://www.extremeprogramming.org/rules/pair.html Pair Programming]
 
 
 
We are going to pair off to do our next assignment. Many of the paired programming principles come from XP (http://www.extremeprogramming.org/ Extreeme Progamming)
 
 
 
Pairs are good because
 
*Pairs keep each other on track
 
*A partner can help when you are stuck
 
*Keep each other accountable
 
 
 
 
 
Some XP Principles
 
 
 
Fail - If you are having trouble succeeding fail.
 
 
 
Baby Steps - Do the smallest thing that you possible can that moves you in the right direction
 
 
 
If you do decide to dive and conqure the problem please remember that integration process is unpredictable and can be quite difficult. Try to integrate your code often. Try posting up your code and emailing or plan on meeting several times.
 
 
 
When topair programmers are together one you should sit a one computer (yeah that right two of you at one computer) and one should type while the other watches and reflects. Feel free to slide the keyboard back and forth when someone get tired, stuck or has a new idea.
 
 
 
I would like you and your paired partner to create and demonstate classes in c# from the diagram below.
 
 
 
 
 
 
 
==Homework==
 
  
use Pair Programming to make tests and classes from the following UML
+
*Create A Cat Containment and Association Project based off of the followong UML
 +
[[Image:CatConainmentAssociation.PNG]]
  
[[OOP Students Classes Diagram]]
+
The Program should have output similar to
 +
<pre>
 +
Hello I am a CatContainmentAssociation.Cat I'm 10 years old and I weigh 0 My Meo
 +
w sounds like Meow!. punkin doesn't have a toy to play with
 +
Hello I am a CatContainmentAssociation.Cat I'm 10 years old and I weigh 0 My Meo
 +
w sounds like Meow!. punkin plays with SparkleyBall
 +
The Basement LitterBox is clean
 +
The Basement LitterBox is dirty
 +
The Basement LitterBox is clean
 +
</pre>
  
If you need to ad anysupprting methods or propertites that are not on the diagram feel free.
 
 
Create a UML Diagram of your c# classes (not the tv and radio yeah the pong machine and ninja and kungfumonkey and stuff)
 
 
===READ===
 
Chapter 2 Introducin the UML in The Unified Modeling Language Users Guided (hand out)
 
 
Chapter 4 Classes in The Unified Modeling Language Users Guided (hand out)
 
  
quiz #2 next week
+
*Create a fourth class the uses or is used by one of your other classes
 +
**Association
 +
*Create a fifth class the contains or is contained by one of your other classes
 +
**Containment
 +
**Create a UML diagram that show the relationships of your classes post export the diagram as a png (I'll show this in class) post diagram to demo fourth and fifth class

Latest revision as of 16:30, 10 June 2019


Review

Accessibility
restrict the visibility of a class and it's members
Classes
Abstraction that has properties and methods. properties and the nouns and methods are the verbsClasses are used to define objects.
Objects
Instance of a class
Abstraction 
Factor out details to work on fewer concepts at a time
Encapsulation
Allows us to use objects with out completely understanding how everything inside the object works. Encapsulation also allows the internal state of objects to be changed easily without affecting other objects or interfaces. 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
Polymorphism
many forms that have the same attributes and abilities
UML 
Unified Modeling Language.

TODO

Virtual Functions
Functions that can be overridden.
Static
Members that are associayed with a class not an instance of the class

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

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++;
	}

}

Static dougCount Example
dogStatic.cs - source



OverLoading

You can overload a method to make it more flexible.

Simple Bark Method

public class Dog
{
 	public string Name;		// the dog's name
	
	public string BarkSound;	// the sound of the dog's bark
	
	public Dog()
	{
		BarkSound = "Woof!!!";
	}
 
	public string Bark() { 
		string strBark = this.BarkSound;
                barkCount ++;
                return strBark;
	}
    
	public void Eat() {
		//put eat code here 
	}
}

overloaded method that makes a dog bark more than once.

public class Dog
{
 	public string Name;		// the dog's name
	
	public string BarkSound;	// the sound of the dog's bark
	
	public Dog()
	{
		BarkSound = "Woof!!!";
	}
 
	public string Bark() { 
		string strBark = this.BarkSound;
                barkCount ++;
                return strBark;
	}
    
	public string Bark(int numBarks) { 
		string strBark = "";
                for(int i =0; i < numBarks; i++)  //bark many times
                {
                   strBark += this.BarkSound;
                   barkCount ++;
                }
                return strBark;
	}
}

You can overload a method as much as you want as long as each overload has a unique argument signature


Overload Constructor

Overloading the constructor of you class can make it easier to use.

here is a simple dog contructor

public class Dog
{
 	
	public string BarkSound;	// the sound of the dog's bark
	
	public Dog()
	{
		BarkSound = "Woof!!!";
	}
 
}

we can modify this so that we can pass in the sound of the dogs bark when the object is created

public class Dog
{
 	
	public string BarkSound;	// the sound of the dog's bark
	
	public Dog(string newBarkSound)
	{
		this.BarkSound = newBarkSound;
	}
 
}

or the name of the dog and the barksound


public class Dog
{
 	
	public string BarkSound;	// the sound of the dog's bark
        public string Name;
	
	public Dog(string newBarkSound, string NewName)
	{
		this.BarkSound = newBarkSound;
                this.Name = newName;

	}
 
}

you can have as many overoads as you want as long as each overload has a unique argument signature




Association - 'Uses A'

A dog uses a hydrant to relieve them self.

//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.");
    }
  }
}

Dog Association example DogHydrant.cs - source

Containment - 'Has A'

A dog has an owner


Dog fido = new Dog("fido");
fido.Owner = new Person("Sue");
//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;
    }
  }


Containment example
DogOwner.cs -source

Homework

  • Create A Cat Containment and Association Project based off of the followong UML

CatConainmentAssociation.PNG

The Program should have output similar to

Hello I am a CatContainmentAssociation.Cat I'm 10 years old and I weigh 0 My Meo
w sounds like Meow!. punkin doesn't have a toy to play with
Hello I am a CatContainmentAssociation.Cat I'm 10 years old and I weigh 0 My Meo
w sounds like Meow!. punkin plays with SparkleyBall
The Basement LitterBox is clean
The Basement LitterBox is dirty
The Basement LitterBox is clean


  • Create a fourth class the uses or is used by one of your other classes
    • Association
  • Create a fifth class the contains or is contained by one of your other classes
    • Containment
    • Create a UML diagram that show the relationships of your classes post export the diagram as a png (I'll show this in class) post diagram to demo fourth and fifth class