OOP Class4

esse quam videri
Revision as of 04:01, 19 January 2006 by Jeff (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Classes and 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 Reasons for organizing code into Classes and Objects

  • avoid spaghetti
  • 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. 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).

Classes are the unique feature that make a programming language an object oriented programming language.

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.

  • granulairity
  • reusability
  • flexabilty
  • performance
  • portability


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#

<csharp>public class SomeClass { }</csharp>

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.

<csharp>// Instantiate SomeClass objects // Declare an instance of the SomeClass class SomeClass firstClass;

// Allocate memory for the dog object firstClass = new SomeClass();

// Declare and Allocate in one like SomeClass secondClass = new SomeClass();</csharp>

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. constructor example

<csharp>public class SomeClass { public SomeClass() { //constructor code } }</csharp>

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

Dog Class


   * string Name
   * int Age
   * int Weight
   * string BarkSound


   * Bark
   * Eat


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. Simple Dog class with constructor

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

Console Example /infod/jeff/classSource/class4/dog.cs 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

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

Console Example dogOverload.cs Web Example

   * dogOverLoad.aspx
   * dogOverLoadWeb.cs

Private instance data members - accessors

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

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

public string Color {

  return color;
  color = value;


//private string color read only private string color;

public string Color {

  return color;


This keyword

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

<csharp>public Time( int CurrentYear, int CurrentDay) {

this.Year = CurrentYear;
this.Day = CurrentDay;


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
           //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;
          color = value;

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

Dog private members, Overloaded with method class definition

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

	private string name;		// the dog's name

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

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

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

   public string About() 

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

       string about = "";

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

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


       return about;


public void Bark() { //make dog bark Console.WriteLine (this.Name + " says " + this.barkSound); //add 1 to the number of times the dog has barked this.barkCount++ ; } public void Eat() { //put eat code here } }</csharp>

console /infod/jeff/classSource/class4/dogOverloadMethodScoped.cs web /infod/jeff/classSource/class4/dogOverLoad.aspx - source aspx /infod/jeff/classSource/class4/dogOverLoad.aspx source cs /infod/jeff/classSource/class4/dogOverloadMethodScopedWeb.cs Real barking dogs... /infod/jeff/classSource/class4/DogBark/Barking dogs

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

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...

In Class Project

In class build traingle class. Properties

  • sideA
  • sideB
  • sideC


  • 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>

tri_class.cs -source


Read Chapter 08 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
  • Three public accessors SideA, SideD, SideC
  • One method Area use the formula from week 4 page
  • Enough other code to demonstrate the functionality of the class

Build a class of your own that describes some real world object Make anthor class of your own. 4 pts. I can be anything be creative. Your own class should have private member variables, accessors, methods, and constructors Quiz Next week on Control Structures, Classes and Objects