Difference between revisions of "OOP Class4"

esse quam videri
Jump to: navigation, search
(Chair Class)
 
(36 intermediate revisions by 4 users not shown)
Line 1: Line 1:
[[Category:OOP]]
+
[[Category:IAM Classes]]
 
=Classes and Objects=
 
=Classes and Objects=
 
==Objects==
 
==Objects==
  
Object-oriented programs are made up of objects. An object packages both data and the procedures that operate on that data. The procedures are typically called methods or operations. An object performs an operation when it recieves a request(or message) from a client. " - Design Patterns Addison Wesley
+
Object-oriented programs are made up of objects.  
 +
:"An object packages both data and the procedures that operate on that data. The procedures are typically called methods or operations. An object performs an operation when it receives a request(or message) from a client. " - Design Patterns Addison Wesley
 
Reasons for organizing code into Classes and Objects
 
Reasons for organizing code into Classes and Objects
  
 
* avoid spaghetti
 
* avoid spaghetti
 +
* organize code into logical sections
 +
* simplify program designs
 
* reuse
 
* reuse
  
Classes are sections of code that describe real world objects. Classes define what properties and methods an object contains. Properties define data members of classes and methods define what classes can do.
+
Classes are sections of code that describe real world objects. Classes define what '''properties''' and '''methods''' an object contains.  
Abstraction
 
  
Humans are always abstracting and naming objects. It is how we identify things. Ojbects are indentied by two this properties(what the have) and methods (what they do).
+
'''Properties''': define data members of classes. Nouns
  
Classes are the unique feature that make a programming language an object oriented programming language.
+
'''Methods''': define what classes can do. Verbs
  
The hardest part about object oriented programming is choosing how to build and implemt these abstractions. There are many factors that affect these descicions. It can ofetn be very diffuclt to find a balance between all of the factors.
+
===Abstraction===
  
* granulairity
+
Humans are always abstracting and naming objects. It is how we identify things. Objects are identified by two things: properties(what the have) and methods (what they do).
* reusability
+
 
* flexabilty
+
Classes are used to define objects.
* performance
+
 
 +
The hardest part about object oriented programming is choosing how to build and implement these abstractions. There are many factors that affect these decisions. It can often be very difficult to find a balance between all of the factors.
 +
 
 +
* granularity
 +
:the size and acuracy of you abstraction
 +
* re usability
 +
:simpler objects are more reusable
 +
* flexibility
 +
:specialized objects are often less flexible
 
* portability
 
* portability
 +
:encapsulated objects make it easier to port to other languages
  
 
==Encapsulation==
 
==Encapsulation==
Line 32: Line 43:
 
a simple example of class syntax in c#
 
a simple example of class syntax in c#
  
<csharp>public class SomeClass { }</csharp>
+
<syntaxhighlight lang="csharp">public class Dog{ }</syntaxhighlight>
  
 
class syntax full
 
class syntax full
Line 39: Line 50:
 
   {class body}
 
   {class body}
  
Objects are instances of classes. For instance a Dog class may describe what dogs are like. All dogs have specific properties like height, weight, color. Dog also have methods like bark. My dog rover is a specific instance of the dog class.
+
Objects are instances of classes. For instance a Dog class may describe what dogs are like.  
 +
 
 +
All dogs have specific properties like height, weight, color. Dog also have methods like bark. My dog rover is a specific instance of the dog class.
  
 
 
 
 
<csharp>// Instantiate SomeClass objects
+
<syntaxhighlight lang="csharp">// Instantiate Dog objects
// Declare an instance of the SomeClass class
+
// Declare an instance of the Dog class
SomeClass firstClass;
+
Dog firstDog;
  
 
// Allocate memory for the dog object
 
// Allocate memory for the dog object
firstClass = new SomeClass();
+
firstDog = new Dog();
  
 
// Declare and Allocate in one like
 
// Declare and Allocate in one like
SomeClass secondClass = new SomeClass();</csharp>
+
Dog secondDog = new Dog();</syntaxhighlight>
  
The new keyword call the classes constructor which allocated memory on the stack for the object if you do not provide a constructor then a default constructor will be provided.
+
The '''new''' keyword call the classes '''constructor''' which allocated memory on the stack for the object.  
constructor example
 
  
 +
access modifier restrictions
  
<csharp>public class SomeClass
+
{|-
{
 
public SomeClass()
 
{
 
//constructor code
 
}
 
}</csharp>
 
 
 
access modifier restrictions
 
(|-
 
 
|public || No restrictions available to all members of the class.
 
|public || No restrictions available to all members of the class.
 
|-
 
|-
Line 76: Line 80:
 
|protected internal ||Same as protected and internal
 
|protected internal ||Same as protected and internal
 
|}
 
|}
 
  
 
==Chair Class==
 
==Chair Class==
Line 97: Line 100:
 
==Dog Class==
 
==Dog Class==
 
===Fields===
 
===Fields===
Micorsoft has started call ing public variables fields
+
Microsoft has started call ing public variables fields
  
 
* string Name
 
* string Name
Line 115: Line 118:
 
==Constructors==
 
==Constructors==
  
A classes constructror is the method that is run when an instance of the class is created. If you do not provide a constructor the complier provides one for you. The contructor is used to initiate all memeber properties. Unlike intrinsic types variables that are not initialized will be set to 0 or "" or null by the compiler in the default constructor.
+
A classes constructor is the method that is run when an instance of the class is created. If you do not provide a constructor the complier provides one for you. The constructor is used to initiate all member properties. Unlike intrinsic types variables that are not initialized will be set to 0 or "" or null by the compiler in the default constructor.
 +
 
 +
The constructor allows you to set default values for the properties of the class. If you do not provide a constructor then a default constructor will be provided. The default constructor will initialize all of the properties in the class to empty/zero/null values.
 +
 
 +
constructor example
 +
 
 +
<syntaxhighlight lang="csharp">public class Dog
 +
{
 +
//Same name as the Class and no return type
 +
        public Dog()
 +
{
 +
//constructor code set initial value for local objects
 +
}
 +
}</syntaxhighlight>
 +
 
 
Simple Dog class with constructor
 
Simple Dog class with constructor
  
<csharp>//Dog simple class definition
+
<syntaxhighlight lang="csharp">//Dog simple class definition
 
public class Dog
 
public class Dog
 
{
 
{
Line 137: Line 154:
 
//put eat code here  
 
//put eat code here  
 
}
 
}
}</csharp>
+
}</syntaxhighlight>
  
 
Console Example [http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dog1/Dog.cs Dog.cs] <br />
 
Console Example [http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dog1/Dog.cs Dog.cs] <br />
  
Notice that the dog class cannot run. In fact it won't even compile with csc ad an exe. You will get error
+
==In Class==
<pre>error CS5001: Program 'c:\backup\csharp\class4\Dog.exe' does not have an entry point defined</pre>
 
if you try. since the dog class does not have a main method and if we use proper abstaction and ecapsulation then I don't believe
 
that the dog class should have a main method. We will need to write another class that will test drive out dog class. This small program
 
often classed a test or driver class will demonstate how our dog class works. This class will be for demonstation/debug purposes only and will usualy be discarded in the final product.
 
 
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dog1/dogTester.cs DogTester.cs]
 
 
 
Notice that this class will also not compile on it's own. You will get
 
<pre>dogTester.cs(19,3): error CS0246: The type or namespace name 'Dog' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(22,3): error CS0103: The name 'milo' does not exist in the class or namespace 'DogTester'
 
dogTester.cs(25,32): error CS0246: The type or namespace name 'milo' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(26,31): error CS0246: The type or namespace name 'milo' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(27,34): error CS0246: The type or namespace name 'milo' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(28,37): error CS0246: The type or namespace name 'milo' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(31,3): error CS0246: The type or namespace name 'Dog' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(32,3): error CS0246: The type or namespace name 'fido' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(33,37): error CS0246: The type or namespace name 'fido' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(34,31): error CS0246: The type or namespace name 'fido' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(35,34): error CS0246: The type or namespace name 'fido' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(36,37): error CS0246: The type or namespace name 'fido' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(39,3): error CS0246: The type or namespace name 'Dog' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(40,3): error CS0246: The type or namespace name 'roover' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(41,3): error CS0246: The type or namespace name 'roover' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(42,3): error CS0246: The type or namespace name 'roover' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(43,37): error CS0246: The type or namespace name 'roover' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(44,31): error CS0246: The type or namespace name 'roover' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(45,34): error CS0246: The type or namespace name 'roover' could not be found (are you missing a using directive or an assembly reference?)
 
dogTester.cs(46,37): error CS0246: The type or namespace name 'roover' could not be found (are you missing a using directive or an assembly reference?)</pre> 
 
 
 
You can complile the Dog.cs file as a dll (shared library)
 
<pre>csc /t:library /out:Dog.dll Dog.cs</pre>
 
This will produce the Dog.dll file which will allow us to compile the Test class with a refence to the Dog.dll
 
<pre>csc dogTester.cs /reference:Dog.dll</pre>
 
Now we have a working dogTester.exe that is linked to Dog.dll.
 
 
 
Sometimes during devolpment of small classes it is easier to combine the new class and the test class into one file.
 
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dog1/dogTest.cs dogTest.cs]
 
 
 
  
 +
  Make and compile a Cat class with a test class.
 +
  *Draw UML for the Cat Class
 +
  *Write test class
 +
  *Compile and test test class
 +
  *Make Dog class
 +
  *Test Dog class with test class
  
Visual Studio will help us out later by linking all of our references for us. If I don't feel like maintaining a VS project often I will just make a batch file similar to [http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dog1/dogTest.bat dogTest.bat]
+
==OverLoading Constructors==
  
There is also an open source build tool NAnt http://nant.sourceforge.net/
+
Overloading a constructor allows object creation to happen in different ways with different parameters. The class can be overloaded to accept different parameters but each constructor method must have a unique parameter signature.
 
 
<!--Web Example
 
 
 
    * /infod/jeff/classSource/class4/dog.aspx - source
 
    * /infod/jeff/classSource/class4/dogWeb.cs -->
 
 
 
==OverLoading Contructors==
 
 
 
OverLoading a consructor allows object creation to happen in different ways with different parameters. The class can be overloaded to accept different parameters but each contructor method must have a unique parameter signature.
 
 
Dog class with overloaded constructor
 
Dog class with overloaded constructor
  
<csharp>//Dog overloaded class definition
+
<syntaxhighlight lang="csharp">//Dog overloaded class definition
 
public class Dog
 
public class Dog
 
{
 
{
Line 225: Line 201:
 
//put eat code here  
 
//put eat code here  
 
}
 
}
}</csharp>
+
        public string About() {
 +
          string strAbout = "";
 +
          strAbout += this.Name;
 +
          strAbout += " " + this.Age;
 +
          strAbout += " " + this.Weight;
 +
          strAbout += " " + this.BarkSound;
 +
          return strAbout;
 +
        }
  
Console Example [http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dogOverload.cs dogOverload.cs]
+
}
  
Web Example
 
  
    * dogOverLoad.aspx
+
}</syntaxhighlight>
    * dogOverLoadWeb.cs
 
  
==Properties Private instance data members - accessors==
+
Console Example [http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dogOverload.cs dogOverload.cs]
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
+
==HomeWork==
  
<csharp>//private string color read/write
+
2 own classes 1 course class
private string color;
 
  
public string Color
+
Build two of your own classes that describes some real world objects then build a test class to demonstrate how your class works. Your own class should have properties, methods, and constructors.
{
+
 
  get
+
The classes should be in the same visual studio project. The use the program class to create new instances of your classes and set properties and call methods. Use Console.Write to show how properties have been changed and the results of calling the methods.
  {
 
  return color;
 
  }
 
  set
 
  {
 
  color = value;
 
  }
 
}
 
  
//private string color read only
+
3 pts. It can be anything be creative.
private string color;
+
2 pts. Create the course class UML below.
  
public string Color
+
[[Image:CourseUML-VS.JPG]]
{
+
[[Image:CousreUML-Dia.png]]
  get
 
  {
 
  return color;
 
  }
 
}</csharp>
 
  
==This keyword==
+
==Links==
 +
* [http://www.csharphelp.com/archives/archive135.html Operator Overloading In C#]
  
The this keyword used within a class refers to the current instance of the class
+
<syntaxhighlight lang="csharp">
 +
using System;
 +
using System.Collections.Generic;
 +
using System.Text;
  
<csharp>public Time( int CurrentYear, int CurrentDay)
+
namespace Cat
 
{
 
{
this.Year = CurrentYear;
+
    class Program
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
 
 
 
<csharp>//Accessor for private color allow color to be set and return color or 'dirty' + color
 
    public string Color
 
 
     {
 
     {
         get
+
         static void Main(string[] args)
 
         {
 
         {
             //if current dog isClean the return dogs color
+
             Console.WriteLine("Hello I'm a cat program");
            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
+
            Cat punkin = new Cat();
{
+
            Cat bella = new Cat();
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() {
+
            punkin.NAME = "punkin";
//make dog bark
+
            punkin.WEIGHT = 5;
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
+
            bella.NAME = "bella";
 +
            bella.WEIGHT = 20;
  
[http://iam.colum.edu/oop/gbrowser.php?file=/classsource/class4/dogOverloadMethodScoped.cs dogOverloadMethodScoped.cs]
+
            Console.WriteLine(punkin.About());
  
 +
            punkin.Meow();
 +
            punkin.Eat();
  
Real barking dogs...
+
            Console.WriteLine(punkin.About());
  
[http://iam.colum.edu/oop/browser/browser.aspx?f=/classsource/class4/DogBark DogBark]
+
            Console.WriteLine(bella.About());
  
an example of how you don't need to know how all of the classes work just how to use them
+
            Console.ReadKey();
 +
        }
 +
    }
  
==Operator Overloading==
+
    public class Cat
 +
    {
  
You can overload operator in c# just like you overload constuctors
+
        //Properties
 +
        public string NAME;
 +
        public int AGE;
 +
        public int WEIGHT;
 +
        public bool isUGLY;
 +
        public bool isStoopid;
  
    * Operator Overloading In C# - www.csharphelp.com
+
        public string MEOWSOUND;
    * Operator Overloading in C# - HowToDoThings.com
 
  
<csharp>//Overloading unary operators
+
        //Constructor
public static return_type operator op (Type t)
+
        public Cat()
{
+
        {
  // Statements
+
            //set seom default values
}
+
            this.NAME = "some cats name";
 +
            this.AGE = 0;
 +
            this.WEIGHT = 47;
 +
            this.isUGLY = true;
 +
            this.isStoopid = true;
  
//Overloading binary operators
+
            this.MEOWSOUND = "Meow!!!!";
public static ClassType operator + ( object lhs, object rhs )
+
        }
{
 
ClassType c
 
//code to implement class addition
 
return c;
 
}</csharp>
 
  
dog addition? extra credit
+
        //Methods
 +
        public void Meow()
 +
        {
 +
            //write meow sound to the console
 +
            Console.WriteLine(this.MEOWSOUND);
 +
        }
  
How could you overload + operator so that it returns a new dog when two dogs are added together...
+
        public void Eat()
 +
        {
 +
            this.WEIGHT++;
 +
            Console.WriteLine("MMMMMM yummy");
 +
        }
  
 +
        public string About()
 +
        {
 +
            string strAbout = "";
 +
            strAbout += this.NAME;
 +
            strAbout += "\n" + this.WEIGHT;
 +
            strAbout += "\n" + this.AGE;
 +
            if (this.isUGLY)
 +
            {
 +
                strAbout += "\nI'm an Ugly cat";
 +
            }
 +
            else
 +
            {
 +
                strAbout += "\nI'm an nice looking cat";
 +
            }
  
 +
            if (this.isStoopid)
 +
            {
 +
                strAbout += "\nI'm an stoopid cat";
 +
            }
  
==In Class Project==
+
            return strAbout;
In class build traingle class.
+
        }
Properties
 
  
* sideA
+
    }
* sideB
 
* sideC
 
  
Methods
+
}
 
+
</syntaxhighlight>
* 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]
 
 
 
==HomeWork==
 
Read Chapter 08 in learning c#.
 
Read Chapter 2 in Head Start Java (hand out)
 
 
 
 
 
<!--Build any example classes you need to from book
 
Finish triangle class 1 pt.
 
triangle class should have
 
  
* three private instance membver variables sideA, sibeB, sideC
+
==Video==
* Three public accessors SideA, SideD, SideC
+
<html>
* One method Area use the formula from week 4 page
+
<script type='text/javascript' src='http://iam.colum.edu/videotutorials/mediaplayer-5.2/swfobject.js'></script>
* Enough other code to demonstrate the functionality of the class
+
<div id='mediaspace2'>This text will be replaced</div>
-->
+
<script type='text/javascript'>
Build a class called Television and a class called Radio.
+
var so = new SWFObject('http://iam.colum.edu/videotutorials/mediaplayer-5.2/player.swf','mpl','800','600','9');so.addParam('allowfullscreen','true')
Make sure you include several fields/properties and methods along with a constructor.
+
;so.addParam('allowscriptaccess','always');
 +
so.addParam('wmode','opaque');
 +
so.addVariable('file','http://iam.colum.edu/screenz/FA13/OOP_MT/OOP_Class4_MT-Tue/OOP_Class4_MT-Tue.mp4');
 +
so.addVariable('autostart','false');
 +
so.write('mediaspace2');
  
Build a test class to demonstate the functionality of your Television and Radio class.
+
</script>
2 pts.
 
  
Build a class of your own that describes some real world object then build a test class to demostrate how your class works.
+
</html>
3 pts. It can be anything be creative.
 
Your own class should have private member variables, accessors, methods, and constructors.
 
 
 
==Links==
 
* [http://www.csharphelp.com/archives/archive135.html Operator Overloading In C#]
 

Latest revision as of 16:29, 10 June 2019

Classes and Objects

Objects

Object-oriented programs are made up of objects.

"An object packages both data and the procedures that operate on that data. The procedures are typically called methods or operations. An object performs an operation when it receives a request(or message) from a client. " - Design Patterns Addison Wesley

Reasons for organizing code into Classes and Objects

  • avoid spaghetti
  • organize code into logical sections
  • simplify program designs
  • reuse

Classes are sections of code that describe real world objects. Classes define what properties and methods an object contains.

Properties: define data members of classes. Nouns

Methods: define what classes can do. Verbs

Abstraction

Humans are always abstracting and naming objects. It is how we identify things. Objects are identified by two things: properties(what the have) and methods (what they do).

Classes are used to define objects.

The hardest part about object oriented programming is choosing how to build and implement these abstractions. There are many factors that affect these decisions. It can often be very difficult to find a balance between all of the factors.

  • granularity
the size and acuracy of you abstraction
  • re usability
simpler objects are more reusable
  • flexibility
specialized objects are often less flexible
  • portability
encapsulated objects make it easier to port to other languages

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. For example you don't need to know how the phone system works in order to use a telephone. All you really need to know to use the phone system is how to dial a phone Classes

Classes are used to create objects. a simple example of class syntax in c#

public class Dog{ }

class syntax full

  [attributes] [access modifiers} class identifier [:base class]
  {class body}

Objects are instances of classes. For instance a Dog class may describe what dogs are like.

All dogs have specific properties like height, weight, color. Dog also have methods like bark. My dog rover is a specific instance of the dog class.


// Instantiate Dog objects
// Declare an instance of the Dog class
Dog firstDog;

// Allocate memory for the dog object
firstDog = new Dog();

// Declare and Allocate in one like
Dog secondDog = new Dog();

The new keyword call the classes constructor which allocated memory on the stack for the object.

access modifier restrictions

public No restrictions available to all members of the class.
private Members marked private are only available to methods of that class.
protected Members marked protected are available to methods of thay class and of classes dreived from that class.
internal Members marked as internal are available to any class within that classes assembly.
protected internal Same as protected and internal

Chair Class

Fields

  • int Height
  • int NumLegs
  • bool HasBack
  • bool HeightAdjustable

Methods

  • RaiseHeight
  • LowerHeight

Chair Class UML

ChairSimpleUML.png

  In class do phone class.

Dog Class

Fields

Microsoft has started call ing public variables fields

  • string Name
  • int Age
  • int Weight
  • string BarkSound

Methods

  • Bark
  • Eat

Dog Class UML

DogSimpleUML.png

Constructors

A classes constructor is the method that is run when an instance of the class is created. If you do not provide a constructor the complier provides one for you. The constructor is used to initiate all member properties. Unlike intrinsic types variables that are not initialized will be set to 0 or "" or null by the compiler in the default constructor.

The constructor allows you to set default values for the properties of the class. If you do not provide a constructor then a default constructor will be provided. The default constructor will initialize all of the properties in the class to empty/zero/null values.

constructor example

public class Dog
{
	//Same name as the Class and no return type
        public Dog()
	{
		//constructor code set initial value for local objects
	}
}

Simple Dog class with constructor

//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 
	}
}

Console Example Dog.cs

In Class

  Make and compile a Cat class with a test class.
  *Draw UML for the Cat Class
  *Write test class
  *Compile and test test class
  *Make Dog class
  *Test Dog class with test class

OverLoading Constructors

Overloading a constructor allows object creation to happen in different ways with different parameters. The class can be overloaded to accept different parameters but each constructor method must have a unique parameter signature. Dog class with overloaded constructor

//Dog overloaded 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 Dog(string newName)
	{
		Name = newName;
		BarkSound = "Woof!!!";
	}
	public Dog(string newName, string newBarkSound )
	{
		Name = newName;
		BarkSound = newBarkSound;
	}

	public void Bark() { 
		//put bark code here
	}
	public void Eat() {
		//put eat code here 
	}
        public string About() {
           string strAbout = "";
           strAbout += this.Name;
           strAbout += " " + this.Age;
           strAbout += " " + this.Weight;
           strAbout += " " + this.BarkSound;
           return strAbout;
        }

}


}

Console Example dogOverload.cs

HomeWork

2 own classes 1 course class

Build two of your own classes that describes some real world objects then build a test class to demonstrate how your class works. Your own class should have properties, methods, and constructors.

The classes should be in the same visual studio project. The use the program class to create new instances of your classes and set properties and call methods. Use Console.Write to show how properties have been changed and the results of calling the methods.

3 pts. It can be anything be creative. 2 pts. Create the course class UML below.

CourseUML-VS.JPG CousreUML-Dia.png

Links

using System;
using System.Collections.Generic;
using System.Text;

namespace Cat
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello I'm a cat program");

            Cat punkin = new Cat();
            Cat bella = new Cat();

            punkin.NAME = "punkin";
            punkin.WEIGHT = 5;

            bella.NAME = "bella";
            bella.WEIGHT = 20;

            Console.WriteLine(punkin.About());

            punkin.Meow();
            punkin.Eat();

            Console.WriteLine(punkin.About());

            Console.WriteLine(bella.About());

            Console.ReadKey();
        }
    }

    public class Cat
    {

        //Properties
        public string NAME;
        public int AGE;
        public int WEIGHT;
        public bool isUGLY;
        public bool isStoopid;

        public string MEOWSOUND;

        //Constructor
        public Cat()
        {
            //set seom default values
            this.NAME = "some cats name";
            this.AGE = 0;
            this.WEIGHT = 47;
            this.isUGLY = true;
            this.isStoopid = true;

            this.MEOWSOUND = "Meow!!!!";
        }

        //Methods
        public void Meow()
        {
            //write meow sound to the console
            Console.WriteLine(this.MEOWSOUND);
        }

        public void Eat()
        {
            this.WEIGHT++;
            Console.WriteLine("MMMMMM yummy");
        }

        public string About()
        {
            string strAbout = "";
            strAbout += this.NAME;
            strAbout += "\n" + this.WEIGHT;
            strAbout += "\n" + this.AGE;
            if (this.isUGLY)
            {
                strAbout += "\nI'm an Ugly cat";
            }
            else
            {
                strAbout += "\nI'm an nice looking cat";
            }

            if (this.isStoopid)
            {
                strAbout += "\nI'm an stoopid cat";
            }

            return strAbout;
        }

    }

}

Video

This text will be replaced