Upload
doque
View
233
Download
2
Embed Size (px)
Citation preview
C#.net Classes and objects 2
Definitions
• Class– creation pattern for objects– mold for casting objects– meta-object– exists at compile-time
• Object– instance of a class– has all props and ops defined in its class
• including inherited ones
class myC
myC myObj
C#.net Classes and objects 3
Definitions (cont’d)
• Interface– in principal a purely abstract class
– used for “can-do” instead of “is-a” relationships.
– removes most needs for multiple inheritance
• this– reference to current object
C#.net Classes and objects 4
Object Relationships
• ”Has-a”-relationship– value-type field containment
– reference-type field association
• Retrieving containment data from a class– copy of data must be made
• Retrieving associated data from a class– copy of reference must be made
– handle or object ID
C#.net Classes and objects 5
Four categories of methods
• constructors– creates new instances of a class
• destructors– removes/destroys instances of a class
• transformers– affect the state of the object
• accessors– reads (parts of) the state of the object
• (predicates)– boolean questions regarding the state of the object
C#.net Classes and objects 6
Four categories - example• constructors
– Stack() // creates new stack with default size– Stack(int size) // creates new stack with size as size
• destructor– // handled by the system. Deallocation of memory, clean-up
procedures• transformers
– push(anElement) // adds an element to the top of the stack– pop() // removes topmost element from stack
• accessors– top() // reads topmost element off of stack– isEmpty() //answers the question whether the stack is empty
or not– isFull() //answers the question whether the stack is full
or not
C#.net Classes and objects 7
Classes - syntax
• attributes class-modifiers partial class identifier type-parameter-list class-base type-parameter-constraints-clauses class body;– attributes (opt)
• user or system defined attributes of the class– class-modifiers (opt)
• new, public, protected, internal, private, abstract, sealed
– partial (opt)– class-base (opt)
• superclass, interface– type-parameter-list– type-parameter-constraints-clauses– class body
• implementation
C#.net Classes and objects 8
Classes - generics
• Allows container classes to be instantiated with a particular type at compile time
• More type-safe than conventional object-based solutions• Instead ofclass Container()…public Object getData();
• you getclass Container <Type-Identifier> ()…public Type-Identifier getData();
C#.net Classes and objects 9
Classes – generics (cont’d)
• where keyword allows for specific properties to be present for generic T
• public class myClass<T>: where T: iComparable– prevents myClass to be instantiated with T that does not
support iComparable interface
• public class myClass<T>: where T new()– makes sure that T has new method with zero parameters
C#.net Classes and objects 10
Abstract classes
• Represent ideas or concepts– what are shapes?– what are mammals?
• Use of abstract classes by inheritance only– no direct object instances– access to derived classes often done using polymorphism
• Abstract classes can have abstract methods– Forces implementation by derived classes
• Opposite of an abstract class is a sealed class– rarely used
C#.net Classes and objects 11
Abstract class syntax
• public abstract class shape
• {– private double x, y;
– public abstract double Area {get;}
• }
• public class Circle:
C#.net Classes and objects 12
Fields
• Fields can be instantiated in more than one way– constructor– at definition
• private– accessible only to class itself
• static– accessible only at class level, not
at object level.• myClass.X is ok• myObject.X is not
class Fields{ public Fields(int x, int y) {
this.x=x; // oky=y; // ok
} private int x; // ok private int y=5; // ok}
class myClass{ public static int X=42;}…myClass myObject = new myClass();
C#.net Classes and objects 13
Fields (cont’d)
• Automatic instantiation– int 0– float 0.0– bool false– reference null– same for non-static as for static fields.
C#.net Classes and objects 14
Fields - readonly
• readonly keyword prohibits writes unless in constructor or initialization
class myClass{
public static readonly int z = 420;public myClass(int x, int y){
this.x=x;this.y=y;
}private readonly int x, y;
}
C#.net Classes and objects 15
Fields - const
• Const fields are static by default
• Initialized at creation
• Only simple types can be const– int
– string
– float
– other numeric formatsclass X{
public const string = ”X is my name”;}
C#.net Classes and objects 16
Static constructors
• Can initialize static fields but not const fields
sealed class Pair{
public static readonly Pair Origin;public Pair(int x, int y){
this.x = x;this.y = y;
}static Pair(){
Origin = new Pair(0,0);}private int x, y;
}
C#.net Classes and objects 17
Class declaration - examplepublic class Document{
private string contents;private string author;public Document(string author, string contents){
this.author = author;this.contents = contents;
}public string Author{
get { return author; }}public string Contents{
get { return contents; }}
}
C#.net Classes and objects 18
Class declaration – Bank Account
public class BankAccount{
private decimal balance;private ulong acctnum = 0;public decimal Balance{
get { return balance; }}// deposit: deposites amount on account// pre: amount >= 0// post: amount has been increased by amountpublic void deposit(decimal amount){
balance = balance + amount;}// withdraw: removes money from account// pre: amount <= Balance// post: amount has been reduced by amountpublic void withdraw(decimal amount){
balance = balance - amount;}
}
C#.net Classes and objects 19
Using bank accountpublic class Bank{
private BankAccount[] accounts;private int size = 10;public Bank(){
accounts = new BankAccount[size];}public Bank(int initialSize){
size = initialSize;accounts = new BankAccount[size];
}public void deposit(int accountNr, decimal amount){
// Todo}public void withdraw(int accountNr, decimal amount){
// Todo}public decimal balance(int accountNr){
// Todo}public int Size{
get { return size; }}
}
C#.net Classes and objects 20
Inheritance
• All classes inherit from something
• If no explicit base class is given, the class implicitly inherits from class Object
• All classes are hence descendants of Object, either directly or indirectly
Object
myClass1 myClass3
myClass2
C#.net Classes and objects 21
Methods provided by Object
• Object()• virtual bool Equals(Object o)
– compares for physical instance equality• bool ReferenceEquals(Object o1, Object o2)
– compares for reference equality• static bool Equals(Object o1, Object o2)
– compares two objects for physical instance equality• virtual int GetHashCode()
– returns unique integer code for any object• Type GetType()
– returns an object’s type• virtual string ToString()
– converts an object to its string representation
C#.net Classes and objects 22
Inheritance
• Use for ”is-a” relationships– if one class ”is-a” specialization of another class, it can
inherit.
• Not copy-paste inheritance, ie instead of writing the same code twice– makes inheritance hierarchy difficult to understand
• When relationship is ”can-do”, use interfaces instead– Helps in keeping the inheritance tree consistent and
understandable
C#.net Classes and objects 23
Reasons for inheritance
• Building logical structure for data– polymorphism– ”is-a” important
• Extending existing classes– ex. new button
• Do not use inheritance to avoid writing code alone– better to use copy-paste or some pattern instead
C#.net Classes and objects 24
Inheritance – amoral examplepublic class Pris{
public Pris(){
Console.WriteLine("Pris created");}
}public class TobaccoProduct{
public virtual void Use(){}
}
C#.net Classes and objects 25
Amoral example (cont’d)public class Snus : TobaccoProduct{
public virtual Pris makePris(){
// bakaConsole.WriteLine("Baking snus");return new Pris();
}public void putPrisUnderLapp(){
Console.WriteLine("Inserting snus");}public void remove(){
Console.WriteLine("Removing snus");}public override void Use(){
makePris();putPrisUnderLapp();//waít(aWhile);remove();
}}
C#.net Classes and objects 26
Amoral example (cont’d)
public class Portionssnus : Snus{
public override Pris makePris(){
Console.WriteLine("Getting smurfblöja");// ta upp en ur dosanreturn new Pris();
}}
C#.net Classes and objects 27
Polymorphism – setting upusing System;
public class Line : DrawingObject{ public override void Draw() { Console.WriteLine("I'm a Line."); }}
public class Circle : DrawingObject{ public override void Draw() { Console.WriteLine("I'm a Circle."); }}
public class Square : DrawingObject{ public override void Draw() { Console.WriteLine("I'm a Square."); }}
public class DrawingObject{
public virtual void Draw(){ Console.WriteLine("I'm just a generic drawing object.");}
}
C#.net Classes and objects 28
Using polymorphismclass DrawList{
private List<DrawingObject> _list;public DrawList(){
_list = new List<DrawingObject>();}public DrawingObject get(int pos){
return _list[pos];}public void add(DrawingObject drawO){
_list.Add(drawO);}public int size(){
return _list.Count;}
}
C#.net Classes and objects 30
Excercise – Food dishes
• What would the class diagram look like for food dishes?– Think recepie database
– What interfaces should exist?
– How can we organize the objects to optimize searching?
C#.net Classes and objects 31
Excercise – Relationships
• A game engine for a ”Sims”-clone should be developed– People
– Interactions between people
– Who knows who?
– Who is related to whom?
– Professions
– Interfaces