Difference between revisions of "OOP Class5"

esse quam videri
Jump to: navigation, search
 
(32 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Category:OOP]]
+
[[Category:IAM Classes]]
 
==This keyword==
 
==This keyword==
  
 
The this keyword used within a class refers to the current instance of the class
 
The this keyword used within a class refers to the current instance of the class
  
<csharp>public Time( int CurrentYear, int CurrentDay)
+
<syntaxhighlight lang="csharp">public Time( int CurrentYear, int CurrentDay)
 
{
 
{
 
  this.Year = CurrentYear;
 
  this.Year = CurrentYear;
 
  this.Day = CurrentDay;
 
  this.Day = CurrentDay;
}</csharp>
+
}</syntaxhighlight>
  
  
  
==access-modifiers==
+
==What is UML==
public +
+
;UML : Unified Modeling Language.  
:most permissive access. No restrictions on access
+
:"A modeling language is a language whose vocabulary and rules focus on the conceptual and physical representation of a system"
private -
+
The Unified Modeling Language User Guide, Booch Rumbaugh Jacobson
:least permissive access level. Only available to the class in which it was declared
+
ACM Press, Addison Wesley 1999 ISBN 0201571684
protected #
+
[http://www.amazon.com/gp/product/0201571684/104-7742183-3467114?v=glance&n=283155 The Unified Modeling Language User Guide]
:accessible within its class and by derived classes
+
==Simple Notation==
internal
+
Class notation in UML
:accessible only within files in the same assembly
 
protected internal
 
:combination of protected and internal
 
Public Dog
 
[[Image:DogSimpleUML.png]]
 
  
Dog with private age
+
The name of the Class should go inside of a box
[[Image:DogsimpleAgePrivate.png]]
 
  
==Properties Private instance data members - accessors==
+
{| align="center" cellspacing="0" style="border:2px solid black;"
Micorsoft has stared calling private varables with accessors Properties
+
|Class Name
 +
|}
  
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
+
Then Two lines are added. The first line separates Attributes. The second line separates Operations.
private string color;
+
Attributes are the equivalent of fields or properties in c# and Operations are the same as methods.
  
public string Color
+
{|  align="center" border = 0
{
+
|
  get
 
  {
 
  return color;
 
  }
 
  set
 
  {
 
  color = value;
 
  }
 
}
 
  
//private string color read only
+
{|  cellspacing="0" style="border:2px solid black;"
private string color;
+
|Class Name
 +
|-
 +
| style="border-Top:2px solid black;" |&nbsp;
 +
|-
 +
| style="border-Top:2px solid black;" |&nbsp;
 +
|}
  
public string Color
+
|
{
 
  get
 
  {
 
  return color;
 
  }
 
}</csharp>
 
  
 +
{| align="center" cellspacing="0" Border = 0
 +
| <--'''Class Name'''
 +
|-
 +
|  <--'''Attributes'''
 +
|-
 +
| <--'''Opertaions'''
 +
|}
  
Another property that is a good candidate for a private instance data member is the dogs age
+
|}
  
<csharp>
 
private string age;
 
  
public int Age
+
A Rectagle Class might look like this
{
 
  //age can only be accessed with get there is no set accessor
 
  //age must be set with HappyBirthday()
 
  get
 
  {
 
  return age;
 
  }
 
}
 
  
public int HappyBirthday()
+
{|  align="center" cellspacing="0" style="border:2px solid black;"
{
+
|Rectangle
  age++;
+
|-
  return age;
+
| style="border-Top:2px solid black;" | height
}
+
|-
 +
| width
 +
|-
 +
| style="border-Top:2px solid black;" | area()
 +
|-
 +
| add()
 +
|-
 +
| move()
 +
|-
 +
| copy()
 +
|-
 +
| isEmpty()
 +
|}
  
 +
You can also specify Attribute types with a :
  
</csharp>
+
{|  align="center" cellspacing="0" style="border:2px solid black;"
 +
|Rectangle
 +
|-
 +
| style="border-Top:2px solid black;" | height : Float
 +
|-
 +
| width : Float
 +
|-
 +
| style="border-Top:2px solid black;" | area()
 +
|-
 +
| add()
 +
|-
 +
| move()
 +
|-
 +
| copy()
 +
|-
 +
| isEmpty()
 +
|}
  
===In class===
+
Default vlaues are specified with =  
  
==In Class Project==
+
{|  align="center" cellspacing="0" style="border:2px solid black;"
 +
|Rectangle
 +
|-
 +
| style="border-Top:2px solid black;" | height : Float = 6.0
 +
|-
 +
| width : Float = 4.0
 +
|-
 +
| style="border-Top:2px solid black;" | area()
 +
|-
 +
| add()
 +
|-
 +
| move()
 +
|-
 +
| copy()
 +
|-
 +
| isEmpty()
 +
|}
  
*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 return type are also specifed with a :. Opertor parameter signatures are specified by ( '''name''' : '''Type''' )
Properties
 
  
* sideA
+
{|  align="center" cellspacing="0" style="border:2px solid black;"
* sideB
+
|Rectangle
* sideC
+
|-
 +
| style="border-Top:2px solid black;" | height : Float = 6.0
 +
|-
 +
| width : Float = 4.0
 +
|-
 +
| style="border-Top:2px solid black;" | area() : Float
 +
|-
 +
| add()(r:Rectangle)
 +
|-
 +
| move()
 +
|-
 +
| copy() :Rectangle
 +
|-
 +
| isEmpty() : Boolean = true
 +
|}
  
Methods
+
==UML Resources==
 +
[http://www.gnome.org/projects/dia/ Dia A Drawing Program]
  
* Area //A method that reurn the area of the triangle
+
[http://dia-installer.sourceforge.net/ Dia for windows]
  
      use Heronian formula which is able to compute the area of a triange by knowing the length of the three sides.
+
[http://iam.colum.edu/oop/browser/browser.aspx?f=/classsource/class6/DiagramDog Dog Diagrams with Dia]
      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
+
==access-modifiers==
double s = (a + b + c) / 2.0;
+
public +
double dArea = Math.Sqrt(s*(s-a)*(s-b)*(s-c));
+
:most permissive access. No restrictions on access
</csharp>
+
private -
 +
:least permissive access level. Only available to the class in which it was declared
  
Once you have built the triangle class build a class to test it.
+
Public Dog
The test class should create a triangle with
+
[[Image:DogSimpleUML.png]]
sideA= 3
 
sideB= 4
 
sideC= 5
 
  
and then display the area as text in the console.
+
Dog with private age
 
+
[[Image:DogsimpleAgePrivate.png]]
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
 
 
 
<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
+
==Dog Examples==
 +
Simple Dog Class from week 5 [http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class6/DiagramDog/DogSimple.cs DogSimple.cs - source]<br />
 +
[[Image:DogSimple.png]]
 +
<syntaxhighlight lang="csharp">using System;
  
<csharp>//Dog private members, Overloaded  with method class definition
+
//Dog simple class definition
 
public class Dog
 
public class Dog
 
{
 
{
  private string name; // the dog's name
+
  public string Name; // the dog's name
private int age; // the dog's age
+
public int Age; // the dog's age
private int weight; // the dog's weight
+
public int Weight; // the dog's weight
private string barkSound; // the sound of the dog's bark
+
public string BarkSound; // the sound of the dog's bark
private int barkCount; // how many times the dog has barked
 
 
 
 
public Dog()
 
public Dog()
 
{
 
{
barkSound = "Woof!!!";
+
BarkSound = "Woof!!!";
 
}
 
}
public Dog(string newName)
+
 
{
+
public void Bark() {  
name = newName;
+
//put bark code here
barkSound = "Woof!!!";
 
 
}
 
}
public Dog(string newName, string newBarkSound )
+
public void Eat() {
{
+
//put eat code here
name = newName;
 
barkSound = newBarkSound;
 
 
}
 
}
 +
}</syntaxhighlight>
 +
 +
 +
Dog UML with Types
  
public string Name
+
Dog Class with Types from week 4 [http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class6/DiagramDog/DogWithTypes.cs DogWithTypes.cs - source]<br /><br />
{
+
[[Image:DogWithTypes.png]]
get
+
<syntaxhighlight lang="csharp">using System;
{
+
return name;
+
//Dog simple class definition
}
+
public class Dog
set
+
{
{
+
public string Name; // the dog's name
name = value;
+
private int age; // the dog's age
}
+
public int Weight; // the dog's weight
}
+
public string BarkSound; // the sound of the dog's bark
public int Age
+
private int barkCount;    //The number of time the dog has barked
{
+
public Dog()
get
 
{
 
return age;
 
}
 
set
 
{
 
age = value;
 
}
 
}
 
public int Weight
 
 
{
 
{
get
+
BarkSound = "Woof!!!";
{
 
return weight;
 
}
 
set
 
{
 
weight = value;
 
}
 
 
}
 
}
public string BarkSound
+
{
+
public string Bark() {  
get
+
string strBark = this.BarkSound;
{
+
        barkCount ++;
return barkSound;
+
        return strBark;
}
 
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() {
 
public void Eat() {
 
//put eat code here  
 
//put eat code here  
 
}
 
}
}</csharp>
+
}</syntaxhighlight>
  
console
+
==Class Relationships==
 
+
Four Class Relation ships
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dogOverloadMethodScoped.cs dogOverloadMethodScoped.cs]
 
 
 
 
 
Real barking dogs...
 
  
[http://iam.colum.edu/oop/browser/browser.aspx?f=/classsource/class4/DogBark DogBark]
+
* Association - ''Uses A'' [[OOP Class6]]
 +
* Containment - ''Has A'' [[OOP Class6]]
 +
* Inheritance - ''Is A''
 +
* Interfaces - '''implements or derives from''' We'll do this next week in [[OOP Class7]]
  
an example of how you don't need to know how all of the classes work just how to use them
+
==Inheritance - 'Is A'==
  
 +
[http://ia300033.us.archive.org/1/items/arsdigitac04n03/Lecture_03.html 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.
  
 +
'''Sub''' class
 +
: a Sub class is a class that inherits properties and methods from another class. The class that sub class inherits from id the '''Super''' class
 +
'''Super''' class
 +
: a Super class that has other classes that inherit from it.
  
 +
[[Image:DogInheritance.png|frame|right|caption|The Mammal/Dog/Basengi inheritance relationship]]
  
==Shared Members - static members==
+
A '''Basenji''' is an African barkless dog.
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
+
A '''Basenji''' ''is a'' '''Dog'''.
  
<csharp>public class Dog
+
A '''Dog''' ''is a'' '''Mammal'''.
{
 
//some code
 
  
static private int dogCount; // total number of dogs
+
In this case the '''Mammal''' class is the '''Super''' class to the '''Dog'''.
  
public Dog()
+
The '''Basenji''' is the '''Sub''' class to the '''Dog''' class.
{
 
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 />
+
Here is how you would draw this with UML.
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/dogStatic.cs dogStatic.cs] - source
 
  
 +
Lets start with the Dog/Basenji Relationship
  
==Operator Overloading==
+
syntax
  
You can overload operator in c# just like you overload constuctors
+
<syntaxhighlight lang="csharp">public class Basenji : Dog
 
 
    * 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
+
    //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....
 
}
 
}
  
//Overloading binary operators
+
public class Dog
public static ClassType operator + ( object lhs, object rhs )
+
{
{
+
// some dog code...
ClassType c
+
//methods need to be marked virtual or protected to be overridden
//code to implement class addition
+
    public virtual void Bark()  
return c;
+
    {  
}</csharp>
+
        //make dog bark
 +
        Console.WriteLine (this.Name + " says " + this.barkSound);
 +
        //add 1 to the number of times the dog has barked
 +
        this.barkCount++ ;
 +
    }
 +
}</syntaxhighlight>
  
dog addition? extra credit
+
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/BasenjiInhertance.cs BasenjiInhertance.cs] -source
  
How could you overload + operator so that it returns a new dog when two dogs are added together...
+
==Virtual Functions==
  
===Operator Overloading Fraction Class===
+
A class modifier that indicates that a method can be overridden by a derived class.
  
<csharp>public static ClassType operator + ( object lhs, object rhs )
+
By marking a function as '''virtual''' any class a class that sub classes the current class can '''override''' the function
{
 
    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.
+
==Abstract Classes==
Fraction class
+
abstract - A class modifier that specifies that the class must be derived from to be instantiated.
  
    * Create fractions from two numbers x/y or from whole numbers
+
<syntaxhighlight lang="csharp">abstract public class Mammal
    * Convert fractions to wholenumbers int
+
{
    * Convert fractions to float or double
+
public string Birth;
    * OverRide ToString to decribe Fraction
+
public string Skin;
  
 +
public Mammal()
 +
{
 +
Birth = " gives birth to live young.";
 +
Skin = " has Hair.";
 +
}
 +
}</syntaxhighlight>
  
Fraction Class Example of operator overloading.<br />
+
Inheritance example /infod/jeff/classSource/class5/DogMammalInhertance.cs -source
[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...
+
===Polymorphic Types===
  
* Creates a fraction out of integers (ie cast int into fractions)
+
;Polymorphism: poly means 'many' morph means 'form'. So a polymorphic type is many forms that have the same attributes and abilities
* 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==
+
[http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29 Polymorphism (computer science)]
Four Class Relation ships
 
  
* Association - 'Uses A'
+
Different types implementing the same functionality.
* Containment - 'Has A'
 
* Inheritance - 'Is A'
 
* Interfaces - implements or derives from We'll do this next week in [[OOP Class6]]
 
  
==Association - 'Uses A'==
+
[http://www.webopedia.com/TERM/p/polymorphism.html  polymorphism webopedia]
  
A dog uses a hydrant to relieve them self.
+
The C# Station Tutorial - [http://www.csharp-station.com/Tutorials/Lesson09.aspx Lesson 9: Polymorphism]
  
<csharp>//Dog simple class definition
+
<syntaxhighlight lang="csharp">//Mammal class definition is it abstract
public class Dog
+
abstract public class Mammal
 
{
 
{
    //some dog code...
+
public string Name;
   
+
public string Brith;
    public void Relieve(Hydrant h)
+
public string Skin;
    {
 
    h.Clean = false;
 
    }
 
}   
 
  
public class Hydrant
+
public Mammal()
{
+
{
  public string Color; //the color of the hydrant
+
Name = "none";
  public bool Clean;  //if the hydrant is clean or dirty
+
Brith = " gives Brith to live young.";
 
+
Skin = " has Hair.";
  public Hydrant()
+
}
  {
+
    Color = "red";
+
    Clean = true;
+
public Mammal(string newName)
  }
+
{
 
+
Name = newName;
  public override string ToString ()
+
Brith = " gives Brith to live young.";
  {
+
Skin = " has Hair.";
    if (this.Clean == true)
+
}
    {
 
    return ("The " + this.Color + " hydrant is clean.");
 
    }
 
    else
 
    {
 
    return ("The " + this.Color + " hydrant is not clean.");
 
    }
 
  }
 
}</csharp>
 
  
Dog Association example
+
public virtual void Bark()
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/DogHydrant.cs DogHydrant.cs] - source
+
{
 +
Console.WriteLine("Some Mammals Bark.");
 +
}
  
==Containment - 'Has A'==
+
}
A dog has an owner
 
  
 +
//Dog simple class definition
 +
public class Dog : Mammal
 +
{
 +
public string BarkSound; // the sound of the dog's bark
 +
 +
public Dog(string newName)
 +
{
 +
Name = newName;
 +
BarkSound = "Woof!!!";
 +
}
  
<csharp>Dog fido = new Dog("fido");
+
public override void Bark() {
fido.Owner = new Person("Sue");</csharp>
+
base.Bark();
 +
Console.WriteLine(this.Name + " says " + this.BarkSound);
 +
}
 +
public void Eat() {
 +
//put eat code here
 +
}
 +
}
  
<csharp>//Dog simple class definition
+
//a basengi is a barkless dog
public class Dog
+
public class Basenji : Dog
 
{
 
{
    public string Name;        // the dog's name
+
//override constructor
    public string BarkSound;    // the sound of the dog's bark
+
public Basenji(string newName) : base(newName)
    public Person Owner;    // the dogs owner
+
{
   
+
BarkSound = "basenjis don't bark, but they do howl and growl.";
    public Dog(string dogName)
+
}
    {
+
        Name = dogName;
+
public override void Bark()
        BarkSound = "Woof!!!";
+
{
    }
+
base.Bark();
 
+
Console.WriteLine("\nBasenjis dont bark.");
    public string Bark() {  
+
}
        string s;
+
        s = this.Name + " says " + this.BarkSound;
+
// some more code....
        //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<br>
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/DogOwner.cs DogOwner.cs] -source
 
 
 
  
 +
}</syntaxhighlight>
  
 +
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/DogPoly.cs DogPoly.cs] -source
  
 
==HomeWork==
 
==HomeWork==
Line 463: Line 391:
 
#Chapter 11 Inheritance and Polymorphism p 134-154
 
#Chapter 11 Inheritance and Polymorphism p 134-154
 
#Chpater 12 Operator Overloading p 155 - 172
 
#Chpater 12 Operator Overloading p 155 - 172
#chapter 13 Structs p 172 - 177 (relax its only 54 pages total)
 
  
 
'''DO'''
 
'''DO'''
 +
Create a super class and a sub class for your class.<br />
  
Extend the class that you worked on last week.<br />
+
http://iam.colum.edu/oop/classsource/class5/ConsoleApplicationInClass.zip
.
 
 
 
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
 
 
 
Extra credit add two dags
 
 
 
roover = fido + milo;
 
  
Quiz 2 next week
+
New One
 +
http://iam.colum.edu/oop/classsource/class5/ConsoleApplicationInClass5.zip
  
 
==Links==
 
==Links==

Latest revision as of 16:30, 10 June 2019

This keyword

The this keyword used within a class refers to the current instance of the class

public Time( int CurrentYear, int CurrentDay)
{
 this.Year = CurrentYear;
 this.Day = CurrentDay;
}


What is UML

UML 
Unified Modeling Language.
"A modeling language is a language whose vocabulary and rules focus on the conceptual and physical representation of a system"

The Unified Modeling Language User Guide, Booch Rumbaugh Jacobson ACM Press, Addison Wesley 1999 ISBN 0201571684 The Unified Modeling Language User Guide

Simple Notation

Class notation in UML

The name of the Class should go inside of a box

Class Name


Then Two lines are added. The first line separates Attributes. The second line separates Operations. Attributes are the equivalent of fields or properties in c# and Operations are the same as methods.

Class Name
 
 
<--Class Name
<--Attributes
<--Opertaions


A Rectagle Class might look like this

Rectangle
height
width
area()
add()
move()
copy()
isEmpty()

You can also specify Attribute types with a :

Rectangle
height : Float
width : Float
area()
add()
move()
copy()
isEmpty()

Default vlaues are specified with =

Rectangle
height : Float = 6.0
width : Float = 4.0
area()
add()
move()
copy()
isEmpty()


Operator return type are also specifed with a :. Opertor parameter signatures are specified by ( name : Type )

Rectangle
height : Float = 6.0
width : Float = 4.0
area() : Float
add()(r:Rectangle)
move()
copy() :Rectangle
isEmpty() : Boolean = true

UML Resources

Dia A Drawing Program

Dia for windows

Dog Diagrams with Dia

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

Public Dog DogSimpleUML.png

Dog with private age DogsimpleAgePrivate.png

Dog Examples

Simple Dog Class from week 5 DogSimple.cs - source
DogSimple.png

using System;

//Dog simple class definition
public class Dog
{
 	public string Name;		// the dog's name
	public int Age;			// the dog's age
	public int Weight;			// the dog's weight
	public string BarkSound;	// the sound of the dog's bark
	
	public Dog()
	{
		BarkSound = "Woof!!!";
	}

	public void Bark() { 
		//put bark code here
	}
	public void Eat() {
		//put eat code here 
	}
}


Dog UML with Types

Dog Class with Types from week 4 DogWithTypes.cs - source

DogWithTypes.png

using System;
 
//Dog simple class definition
public class Dog
{
 	public string Name;		// the dog's name
	private int age;			// the dog's age
	public int Weight;			// the dog's weight
	public string BarkSound;	// the sound of the dog's bark
	private int barkCount;    //The number of time the dog has barked
	public Dog()
	{
		BarkSound = "Woof!!!";
	}
 
	public string Bark() { 
		string strBark = this.BarkSound;
        barkCount ++;
        return strBark;
	}
    
	public void Eat() {
		//put eat code here 
	}
}

Class Relationships

Four Class Relation ships

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

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.

Sub class

a Sub class is a class that inherits properties and methods from another class. The class that sub class inherits from id the Super class

Super class

a Super class that has other classes that inherit from it.
The Mammal/Dog/Basengi inheritance relationship

A Basenji is an African barkless dog.

A Basenji is a Dog.

A Dog is a Mammal.

In this case the Mammal class is the Super class to the Dog.

The Basenji is the Sub class to the Dog class.

Here is how you would draw this with UML.

Lets start with the Dog/Basenji Relationship

syntax

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

BasenjiInhertance.cs -source

Virtual Functions

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

By marking a function as virtual any class a class that sub classes the current class can override the function

Abstract Classes

abstract - A class modifier that specifies that the class must be derived from to be instantiated.
abstract public class Mammal
{
	public string Birth;
	public string Skin;

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

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

Polymorphic Types

Polymorphism
poly means 'many' morph means 'form'. So a polymorphic type is many forms that have the same attributes and abilities

Polymorphism (computer science)

Different types implementing the same functionality.

polymorphism webopedia

The C# Station Tutorial - Lesson 9: Polymorphism

//Mammal class definition is it abstract
abstract public class Mammal
{
	public string Name;
	public string Brith;
	public string Skin;

	public Mammal()
	{
		Name = "none";
		Brith = " gives Brith to live young.";
		Skin = " has Hair.";
	}
	
	
	public Mammal(string newName)
	{
		Name = newName;
		Brith = " gives Brith to live young.";
		Skin = " has Hair.";
	}

	public virtual void Bark()
	{
		Console.WriteLine("Some Mammals Bark.");
	}

}

//Dog simple class definition
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 
	}
}

//a basengi is a barkless dog
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....
}	

}

DogPoly.cs -source

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

DO Create a super class and a sub class for your class.

http://iam.colum.edu/oop/classsource/class5/ConsoleApplicationInClass.zip

New One http://iam.colum.edu/oop/classsource/class5/ConsoleApplicationInClass5.zip

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