Difference between revisions of "OOP Class5"

esse quam videri
Jump to: navigation, search
 
 
(85 intermediate revisions by 3 users not shown)
Line 1: Line 1:
Class Relationshipd
+
[[Category:IAM Classes]]
 +
==This keyword==
  
Operator Overloading
+
The this keyword used within a class refers to the current instance of the class
  
<csharp>public static ClassType operator + ( object lhs, object rhs )
+
<syntaxhighlight lang="csharp">public Time( int CurrentYear, int CurrentDay)
 
{
 
{
    ClassType c
+
this.Year = CurrentYear;
    //code to implement class addition
+
this.Day = CurrentDay;
    return c;
+
}</syntaxhighlight>
}</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
 
  
 +
==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
 +
[http://www.amazon.com/gp/product/0201571684/104-7742183-3467114?v=glance&n=283155 The Unified Modeling Language User Guide]
 +
==Simple Notation==
 +
Class notation in UML
  
Fraction Class Example of operator overloading.
+
The name of the Class should go inside of a box
/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.
+
{| align="center" cellspacing="0" style="border:2px solid black;"
Using /infod/jeff/classSource/class5/fractionDone_NoTest.cs create a test class or web page that...
+
|Class Name
 +
|}
  
    * 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
 
  
 +
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.
  
More objects
+
{|  align="center" border = 0
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
+
{|  cellspacing="0" style="border:2px solid black;"
 +
|Class Name
 +
|-
 +
| style="border-Top:2px solid black;" |&nbsp;
 +
|-
 +
| style="border-Top:2px solid black;" |&nbsp;
 +
|}
  
<csharp>public class Dog
+
|
{
+
 
//some code
+
{| align="center" cellspacing="0" Border = 0
 +
| <--'''Class Name'''
 +
|-
 +
|  <--'''Attributes'''
 +
|-
 +
| <--'''Opertaions'''
 +
|}
 +
 
 +
|}
 +
 
 +
 
 +
A Rectagle Class might look like this
 +
 
 +
{|  align="center" cellspacing="0" style="border:2px solid black;"
 +
|Rectangle
 +
|-
 +
| 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 :
 +
 
 +
{|  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()
 +
|}
 +
 
 +
Default vlaues are specified with =
 +
 
 +
{|  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()
 +
|}
 +
 
 +
 
 +
Operator return type are also specifed with a :. Opertor parameter signatures are specified by ( '''name''' : '''Type''' )
  
static private int dogCount; // total number of dogs
+
{|  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() : Float
 +
|-
 +
| add()(r:Rectangle)
 +
|-
 +
| move()
 +
|-
 +
| copy() :Rectangle
 +
|-
 +
| isEmpty() : Boolean = true
 +
|}
  
public Dog()
+
==UML Resources==
{
+
[http://www.gnome.org/projects/dia/ Dia A Drawing Program]
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
+
[http://dia-installer.sourceforge.net/ Dia for windows]
  
Class Relationships
+
[http://iam.colum.edu/oop/browser/browser.aspx?f=/classsource/class6/DiagramDog Dog Diagrams with Dia]
Four Class Relation ships
 
  
    * Association - 'Uses A'
+
==access-modifiers==
    * Containment - 'Has A'
+
public +
    * Inheritance - 'Is A'
+
:most permissive access. No restrictions on access
    * Interfaces - implements or derives from
+
private -
 +
:least permissive access level. Only available to the class in which it was declared
  
 +
Public Dog
 +
[[Image:DogSimpleUML.png]]
  
Association - 'Uses A'
+
Dog with private age
 +
[[Image:DogsimpleAgePrivate.png]]
  
A dog uses a hydrant to relieve them self.
+
==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 simple class definition
+
//Dog simple class definition
 
public class Dog
 
public class Dog
 
{
 
{
    //some dog code...
+
public string Name; // the dog's name
   
+
public int Age; // the dog's age
    public void Relieve(Hydrant h)
+
public int Weight; // the dog's weight
    {
+
public string BarkSound; // the sound of the dog's bark
    h.Clean = false;
+
    }
+
public Dog()
}  
+
{
 +
BarkSound = "Woof!!!";
 +
}
  
public class Hydrant
+
public void Bark() {  
{
+
//put bark code here
  public string Color; //the color of the hydrant
+
}
  public bool Clean;  //if the hydrant is clean or dirty
+
public void Eat() {
 
+
//put eat code here
  public Hydrant()
+
}
  {
+
}</syntaxhighlight>
    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");
+
Dog UML with Types
fido.Owner = new Person("Sue");
 
  
<csharp>//Dog simple class definition
+
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]]
 +
<syntaxhighlight lang="csharp">using System;
 +
 +
//Dog simple class definition
 
public class Dog
 
public class Dog
 
{
 
{
    public string Name;       // the dog's name
+
public string Name; // the dog's name
    public string BarkSound;   // the sound of the dog's bark
+
private int age; // the dog's age
    public Person Owner;    // the dogs owner
+
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 Dog(string dogName)
+
public void Eat() {
    {
+
//put eat code here
        Name = dogName;
+
}
        BarkSound = "Woof!!!";
+
}</syntaxhighlight>
    }
+
 
 +
==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'==
 +
 
 +
[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]]
 +
 
 +
A '''Basenji''' is an African barkless dog.
  
    public string Bark() {
+
A '''Basenji''' ''is a'' '''Dog'''.
        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
+
A '''Dog''' ''is a'' '''Mammal'''.
  {
 
    public string Name;      //the color of the hydrant
 
   
 
    public Person(string newName)
 
    {
 
      Name = newName;
 
    }
 
  }</csharp>
 
  
 +
In this case the '''Mammal''' class is the '''Super''' class to the '''Dog'''.
  
Containment example /infod/jeff/classSource/class5/DogOwner.cs -source
+
The '''Basenji''' is the '''Sub''' class to the '''Dog''' class.
  
Inheritance - 'Is A'
+
Here is how you would draw this with UML.
  
C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from.
+
Lets start with the Dog/Basenji Relationship
  
A Basenji is an African barkless dog.
 
A Basenji is a dog.
 
 
syntax
 
syntax
  
<csharp>public class Basenji : Dog
+
<syntaxhighlight lang="csharp">public class Basenji : Dog
 
{
 
{
 
     //override constructor
 
     //override constructor
Line 191: Line 276:
 
         this.barkCount++ ;
 
         this.barkCount++ ;
 
     }
 
     }
}</csharp>
+
}</syntaxhighlight>
  
Basenji.cs -source
+
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/BasenjiInhertance.cs BasenjiInhertance.cs] -source
  
Virtual Functions - A class modifier that indicates that a method can be overridden by a derived class.
+
==Virtual Functions==
  
Abstract Classes abstract - A class modifier that specifies that the class must be derived from to be instantiated.
+
A class modifier that indicates that a method can be overridden by a derived class.
  
<csharp>abstract public class Mammal
+
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.
 +
 
 +
<syntaxhighlight lang="csharp">abstract public class Mammal
 
{
 
{
private string birth;
+
public string Birth;
private string skin;
+
public string Skin;
  
 
public Mammal()
 
public Mammal()
 
{
 
{
birth = " gives birth to live young.";
+
Birth = " gives birth to live young.";
skin = " has Hair.";
+
Skin = " has Hair.";
 
}
 
}
 +
}</syntaxhighlight>
 +
 +
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
  
public string Birth
+
[http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29 Polymorphism (computer science)]
{
+
 
get
+
Different types implementing the same functionality.
{
 
return birth;
 
}
 
}
 
public string Skin
 
{
 
get
 
{
 
return skin;
 
}
 
}
 
}</csharp>
 
  
Inheritance example /infod/jeff/classSource/class5/DogMammal.cs -source
+
[http://www.webopedia.com/TERM/p/polymorphism.html  polymorphism webopedia]
  
Polymorphic Types - Different types implementing the same functionality. webopedia polymorphism
+
The C# Station Tutorial - [http://www.csharp-station.com/Tutorials/Lesson09.aspx Lesson 9: Polymorphism]
The C# Station Tutorial - Lesson 9: Polymorphism
 
  
<csharp>abstract public class Mammal
+
<syntaxhighlight lang="csharp">//Mammal class definition is it abstract
 +
abstract public class Mammal
 
{
 
{
private string name;
+
public string Name;
private string birth;
+
public string Brith;
private string skin;
+
public string Skin;
  
 
public Mammal()
 
public Mammal()
 
{
 
{
name = "none";
+
Name = "none";
birth = " gives birth to live young.";
+
Brith = " gives Brith to live young.";
skin = " has Hair.";
+
Skin = " has Hair.";
 
}
 
}
 +
 
 
 
public Mammal(string newName)
 
public Mammal(string newName)
 
{
 
{
name = newName;
+
Name = newName;
birth = " gives birth to live young.";
+
Brith = " gives Brith to live young.";
skin = " has Hair.";
+
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()
 
public virtual void Bark()
 
{
 
{
 
Console.WriteLine("Some Mammals Bark.");
 
Console.WriteLine("Some Mammals Bark.");
 
}
 
}
 +
 
}
 
}
  
 +
//Dog simple class definition
 
public class Dog : Mammal
 
public class Dog : Mammal
 
{
 
{
Line 301: Line 364:
 
}
 
}
  
 +
//a basengi is a barkless dog
 
public class Basenji : Dog
 
public class Basenji : Dog
 
{
 
{
Line 314: Line 378:
 
Console.WriteLine("\nBasenjis dont bark.");
 
Console.WriteLine("\nBasenjis dont bark.");
 
}
 
}
    // some more code....
+
}</csharp>
+
// some more code....
 +
}
  
/infod/jeff/classSource/class5/DogPoly.cs -source
+
}</syntaxhighlight>
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.
+
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class5/DogPoly.cs DogPoly.cs] -source
Syntax
 
  
[ attributes] [access-modifiers] struct identifier
+
==HomeWork==
[:interface-list {struct members}
+
'''READ'''
 
+
#Chapter 9 Inside Methods p 111-123
<csharp>struct Dog
+
#Chapter 11 Inheritance and Polymorphism p 134-154
{
+
#Chpater 12 Operator Overloading p 155 - 172
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.
+
'''DO'''
 +
Create a super class and a sub class for your class.<br />
  
/infod/jeff/classSource/class5/interface.cs -source
+
http://iam.colum.edu/oop/classsource/class5/ConsoleApplicationInClass.zip
/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
+
New One
Namespaces - Maps set of types to a common name.
+
http://iam.colum.edu/oop/classsource/class5/ConsoleApplicationInClass5.zip
 
 
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
 
 
 
<pre>
 
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>
 
</pre>
 
 
 
==HomeWork==
 
Make a class that subclasses you previous class<br />
 
Make a class the uses your previous class<br />
 
  
 
==Links==
 
==Links==
The C# Station Tutorial - Lesson 7: Introduction to Classes
+
[http://www.csharp-station.com/Tutorials/Lesson07.aspx The C# Station Tutorial - Lesson 7: Introduction to Classes]<br>
The C# Station Tutorial - Lesson 7: Lesson 8: Class Inheritance
+
[http://www.csharp-station.com/Tutorials/Lesson08.aspx The C# Station Tutorial - Lesson 8: Class Inheritance]<br>
The C# Station Tutorial - Lesson 9: Polymorphism
+
[http://www.csharp-station.com/Tutorials/Lesson09.aspx The C# Station Tutorial - Lesson 9: Polymorphism]<br>
The C# Station Tutorial - Lesson 10: Properties
+
[http://www.csharp-station.com/Tutorials/Lesson10.aspx The C# Station Tutorial - Lesson 10: Properties]<br>
The C# Station Tutorial - Lesson 12: Structs
+
[http://www.csharp-station.com/Tutorials/Lesson12.aspx The C# Station Tutorial - Lesson 12: Structs]<br>
The C# Station Tutorial - Lesson 13: Interfaces
+
[http://www.csharp-station.com/Tutorials/Lesson13.aspx The C# Station Tutorial - Lesson 13: Interfaces]<br>
C# Fundamentals - tutorial 4
+
[http://www.csharp-station.com/Tutorials/Lesson04.aspx The C# Station Tutorial - Lesson 4: C# Fundamentals]

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