56
String 1

String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Embed Size (px)

DESCRIPTION

Outline CharMethods.cs 31 // handle analyzeButton_Click 32 private void analyzeButton_Click( 33 object sender, System.EventArgs e ) 34 { 35 char character = Convert.ToChar( inputTextBox.Text ); 36 BuildOutput( character ); 37 } // display character information in outputTextBox 40 private void BuildOutput( char inputCharacter ) 41 { 42 string output; output = "is digit: " + 45 Char.IsDigit( inputCharacter ) + " "; output += "is letter: " + 48 Char.IsLetter( inputCharacter ) + " "; output += "is letter or digit: " + 51 Char.IsLetterOrDigit( inputCharacter ) + " "; output += "is lower case: " + 54 Char.IsLower( inputCharacter ) + " "; output += "is upper case: " + 57 Char.IsUpper( inputCharacter ) + " "; output += "to upper case: " + 60 Char.ToUpper( inputCharacter ) + " "; output += "to lower case: " + 63 Char.ToLower( inputCharacter ) + " "; 64

Citation preview

Page 1: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

String

1

Page 2: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

2

Char Methods

• For the char value type, there is a Char class• Most methods are static

– IsLetter– IsDigit– IsLetterOrDigit– IsLower– IsUpper– ToUpper– ToLower– IsPunctuation– IsSymbol– IsWhiteSpace

Page 3: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Outline

CharMethods.cs

31 // handle analyzeButton_Click32 private void analyzeButton_Click(33 object sender, System.EventArgs e )34 {35 char character = Convert.ToChar( inputTextBox.Text );36 BuildOutput( character );37 } 38 39 // display character information in outputTextBox40 private void BuildOutput( char inputCharacter )41 {42 string output;43 44 output = "is digit: " +45 Char.IsDigit( inputCharacter ) + "\r\n";46 47 output += "is letter: " +48 Char.IsLetter( inputCharacter ) + "\r\n";49 50 output += "is letter or digit: " +51 Char.IsLetterOrDigit( inputCharacter ) + "\r\n";52 53 output += "is lower case: " +54 Char.IsLower( inputCharacter ) + "\r\n";55 56 output += "is upper case: " +57 Char.IsUpper( inputCharacter ) + "\r\n";58 59 output += "to upper case: " +60 Char.ToUpper( inputCharacter ) + "\r\n";61 62 output += "to lower case: " +63 Char.ToLower( inputCharacter ) + "\r\n";64

Page 4: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

4

StringConstructor.cs

using System; using System.Windows.Forms;

class StringConstructor {

static void Main( string[] args ) { string output; string originalString, string1, string2, string3, string4; char[] characterArray = {'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };

originalString = "Welcome to C# programming!"; string1 = originalString; string2 = new string( characterArray ); string3 = new string( characterArray, 6, 3 ); string4 = new string( 'C', 5 ); output = "string1 = " + "\"" + string1 + "\"\n" + "string2 = " + "\"" + string2 + "\"\n" + "string3 = " + "\"" + string3 + "\"\n" + "string4 = " + "\"" + string4 + "\"\n";

Page 5: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

String Indexer, Length Property and CopyTo Method

• String indexer

– Retrieval of any character in the string

• Length property

– Returns the length of the string

• CopyTo

– Copies specified number of characters into a char array

Page 6: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

6

StringMethods.cs

using System; using System.Windows.Forms; class StringMethods { static void Main( string[] args ) { string string1, output; char[] characterArray; string1 = "hello there"; characterArray = new char[ 5 ]; output = "string1: \"" + string1 + "\""; output += "\nLength of string1: " + string1.Length;

output += "\nThe string reversed is: "; for ( int i = string1.Length - 1; i >= 0; i-- ) output += string1[ i ];

Page 7: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Comparing Strings

• String comparison

– Greater than

– Less than

• Method Equals

– Test objects for equality

– Return a Boolean

– Uses lexicographical comparison

Page 8: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

8

StringCompare.cs

using System; using System.Windows.Forms; class StringCompare { static void Main( string[] args ) { string string1 = "hello"; string string2 = "good bye"; string string3 = "Happy Birthday"; string string4 = "happy birthday"; string output; // output values of four strings output = "string1 = \"" + string1 + "\"" + "\nstring2 = \"" + string2 + "\"" + "\nstring3 = \"" + string3 + "\"" + "\nstring4 = \"" + string4 + "\"\n\n"; // test for equality using Equals method if ( string1.Equals( "hello" ) ) output += "string1 equals \"hello\"\n"; else output += "string1 does not equal \"hello\"\n"; // test for equality with == if ( string1 == "hello" ) output += "string1 equals \"hello\"\n";

Page 9: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

9

StringStartEnd.cs

using System; using System.Windows.Forms; class StringStartEnd { static void Main( string[] args ) { string[] strings = { "started", "starting", "ended", "ending" }; string output = ""; for ( int i = 0; i < strings.Length; i++ ) if ( strings[ i ].StartsWith( "st" ) ) output += "\"" + strings[ i ] + "\"" + " starts with \"st\"\n"; output += "\n"; // test every string to see if it ends with "ed“ for ( int i = 0; i < strings.Length; i ++ ) if ( strings[ i ].EndsWith( "ed" ) ) output += "\"" + strings[ i ] + "\"" + " ends with \"ed\"\n";

Page 10: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Miscellaneous String Methods

• Method Replace – Original string remain unchanged – Original string return if no occurrence matched

• Method ToUpper– Replace lower case letter– Original string remain unchanged– Original string return if no occurrence matched

• Method ToLower– Replace lower case letter– Original string remain unchanged– Original string return if no occurrence matched

Page 11: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

11

More String Methods

• Method Trim– removes whitespaces at the beginning and end– original string is changed

• Method Replace – Change all occurrences of one char or string with another

one– original string remains unchanged

Page 12: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

12

StringMiscellaneous2.cs

using System; using System.Windows.Forms; class StringMethods2 { static void Main( string[] args ) { string string1 = "cheers!"; string string2 = "GOOD BYE "; string string3 = " spaces "; string output; output = "string1 = \"" + string1 + "\"\n" + "string2 = \"" + string2 + "\"\n" + "string3 = \"" + string3 + "\""; // call method Replace output += "\n\nReplacing \"e\" with \"E\" in string1: \"" + string1.Replace( 'e', 'E' ) + "\""; // call ToLower and ToUpper output += "\n\nstring1.ToUpper() = \"" + string1.ToUpper() + "\"\nstring2.ToLower() = \"" + string2.ToLower() + "\"";

Page 13: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

You have been provided with the following class that implements a phone number directory: public class PhoneBook { public boolean insert(String phoneNum, String name) { ... } public String getPhoneNumber(String name) { ... } public String getName(String phoneNum) { ... } // other private fields and methods }

• PhoneBook does not accept phone numbers that begin with "0" or "1", that do not have exactly 10 digits. It does not allow duplicate phone numbers. insert() returns true on a successful phone number insertion, false otherwise. getPhoneNumber() and getName() return null if they cannot find the desired entry in the PhoneBook.

• Design and implement a subclass of PhoneBook called YellowPages (including all of the necessary fields and methods) that supports the following additional operations.

• Retrieve the total number of phone numbers stored in the directory. • Retrieve the percentage of phone numbers stored in the directory that

are "810" numbers (that have area code "810").

Page 14: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

What will happen when you attempt to compile and run this code?

class Base{abstract public void myfunc();public void another(){console.writeline("Another method");}}

public class Abs : Base{public static void main(String argv[]){Abs a = new Abs();a.amethod();}

public void myfunc(){ console.writeline("My func");}

public void amethod(){myfunc();}}

Page 15: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

15

Derived-Class-Object to Base-Class-Object Conversion

• Class hierarchies

– Can assign derived-class objects to base-class references

– Can explicitly cast between types in a class hierarchy

• An object of a derived-class can be treated as an object of its base-class

– Array of base-class references that refer to objects of many derived-class types

– Base-class object is NOT an object of any of its derived classes

Page 16: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Working with Override Methods You can only override identical inherited virtual methods

You must match an override method with its associated virtual method

You can override an override method You cannot explicitly declare an override method as virtual You cannot declare an override method as static or private

class Token{ ... public int LineNumber( ) { ... } public virtual string Name( ) { ... } }class CommentToken: Token{ ... public override int LineNumber( ) { ... } public override string Name( ) { ... }}

Page 17: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Working with the new Keyword

• Hide both virtual and non-virtual methods

• Resolve name clashes in code• Hide methods that have identical signatures

class Token{ ... public int LineNumber( ) { ... } public virtual string Name( ) { ... } }class CommentToken: Token{ ... new public int LineNumber( ) { ... } public override string Name( ) { ... }}

Page 18: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

18 using System; // Point class definition implicitly inherits from Object public class Point { // point coordinate private int x, y; // default constructor public Point() { // implicit call to Object constructor occurs here } public Point( int xValue, int yValue ) { // implicit call to Object constructor occurs here X = xValue; Y = yValue; } public int X { get { return x; }

Page 19: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

set { x = value; // no need for validation } } // end property X // property Y public int Y { get { return y; } set { y = value; // no need for validation } } // end property Y // return string representation of Point public override string ToString() { return "[" + X + ", " + Y + "]"; } } // end class Point

19

Page 20: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

20 using System; // Circle class definition inherits from Point public class Circle : Point { private double radius; // circle's radius // default constructor public Circle() { // implicit call to Point constructor occurs here } public Circle( int xValue, int yValue, double radiusValue ) : base( xValue, yValue ) { Radius = radiusValue; } // property Radius public double Radius { get { return radius; }

Page 21: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

21 set { if ( value >= 0 ) // validate radius radius = value; } } // end property Radius public double Diameter() { return Radius * 2; } public double Circumference() { return Math.PI * Diameter(); } public virtual double Area() { return Math.PI * Math.Pow( Radius, 2 ); } public override string ToString() { return "Center = " + base.ToString() + "; Radius = " + Radius; } } // end class Circle

Page 22: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

22 using System; using System.Windows.Forms;class PointCircleTest { // main entry point for application. static void Main( string[] args ) { Point point1 = new Point( 30, 50 ); Circle circle1 = new Circle( 120, 89, 2.7 );

string output = "Point point1: " + point1.ToString() + "\nCircle circle1: " + circle1.ToString(); // use 'is a' relationship to assign // Circle circle1 to Point reference Point point2 = circle1;output += "\n\nCCircle circle1 (via point2): " + point2.ToString(); // downcast (cast base-class reference to derived-class // data type) point2 to Circle circle2 Circle circle2 = ( Circle ) point2; output += "\n\nCircle circle1 (via circle2): " + circle2.ToString(); output += "\nArea of circle1 (via circle2): " + circle2.Area().ToString( "F" );

Page 23: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

23 // attempt to assign point1 object to Circle reference if ( point1 is Circle ) { circle2 = ( Circle ) point1; output += "\n\ncast successful"; } else { output += "\n\npoint1 does not refer to a Circle"; } MessageBox.Show( output, "Demonstrating the 'is a' relationship" ); } // end method Main } // end class PointCircleTest

Page 24: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

24

public class EmployeeMain {public static void printInfo(Employee empl) {Console.writeLine("salary = " + empl.getSalary());Console.writeLine("days = " + empl.getVacationDays());Console.writeLine();}public static void main(String[] args) {Lawyer lisa = new Lawyer();Secretary steve = new Secretary();printInfo(lisa);printInfo(steve);}}

Benefits of polymorphism

A method declaring in its argument list a super class data type can receive an object of any of its subclasses.

polymorphism

With polymorphism, it is possible to design and implement systems that are more easily extensible.Programs can be written to process even objects of types that do not exist when the program is underdevelopment.

Page 25: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

25

abstract class A{public abstract void m();}

class B : A {public void m(){Console.writeLine("Hello from class B");}}

class C : A {public void m(){Console.writeLine("Hello from class C");}}

public class Test{public static void m2(A a1){a1.m();}

public static void main (String [] arg){C c1=new C();m2(c1);}}

Benefits of Abstract methods and Polymorphism

Page 26: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

26

You can declare arrays of superclass types, and store objects of any subtype as elements.

Benefits of polymorphism

public class Test {public static void Main(String[] args) {Employee[] employees = {new Lawyer(), new Secretary(),

new Marketer(), new LegalSecretary()};for (int i = 0; i < employees.length; i++) {Console.writeLine("salary = " +employees[i].getSalary());Console.writeLine("vacation days="+employees[i].getVacationDays());Console.writeLine();

} }}

Example

Page 27: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

27

Interfaces

• Interfaces specify the public services (methods and properties) that classes must implement

• Interfaces provide no default implementations vs. abstract classes which may provide some default implementations

• Interfaces are used to “bring together” or relate disparate objects that relate to one another only through the interface

Page 28: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

28

Interfaces

• Interfaces are defined using keyword interface• Use inheritance notation to specify a class

implements an interface (ClassName : InterfaceName)

• Classes may implement more than one interface (a comma separated list of interfaces)

• Classes that implement an interface, must provide implementations for every method and property in the interface definition

Page 29: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

public interface IDelete { void Delete();}public class TextBox : IDelete { public void Delete() { ... }}public class Car : IDelete { public void Delete() { ... }}

TextBox tb = new TextBox();tb.Delete();

Car c = new Car();iDel = c;iDel.Delete();

Interfaces Example

Page 30: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Declaring Interfaces

• Syntax: Use the interface keyword to declare methods

interface IToken{ int LineNumber( ); string Name( );}

IToken« interface »

LineNumber( )Name( )

No method bodiesNo method bodies

Interface names should Interface names should begin with a capital “I”begin with a capital “I”

No access specifiersNo access specifiers

Page 31: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Implementing Multiple Interfaces• A class can implement zero or more interfaces

• An interface can extend zero or more interfaces• A class can be more accessible than its base interfaces • An interface cannot be more accessible than its base interfaces • A class must implement all inherited interface methods

interface IToken{ string Name( );}interface IVisitable{ void Accept(IVisitor v);}class Token: IToken, IVisitable{ ...}

IToken« interface »

IVisitable« interface »

Token« concrete »

Jon Jagger
All method declarations must name the parameters
Page 32: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Comparing Abstract Classes to Interfaces

• Similarities– Neither can be instantiated– Neither can be sealed

• Differences– Interfaces cannot contain any implementation– Interfaces cannot declare non-public members– Interfaces cannot extend non-interfaces

Page 33: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

33

public interface Ishape { // classes that implement IShape must implement these methods // and this property double Area(); double Volume(); string Name { get; } }

Page 34: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

34

// an x-y coordinate pair. using System; public class Point3 : Ishape { private int x, y; // Point3 coordinates public Point3(){ } // constructor public Point3( int xValue, int yValue ) { X = xValue; Y = yValue; } // property X public int X { get { return x; }

Page 35: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

3532 set33 {34 x = value;35 }36 }37 39 public int Y40 {41 get42 {43 return y;44 }45 46 set47 {48 y = value;49 }50 }51 52 // return string representation of Point3 object53 public override string ToString()54 {55 return "[" + X + ", " + Y + "]";56 }57 58 // implement interface IShape method Area59 public virtual double Area()60 {61 return 0;62 }63

Page 36: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

3664 // implement interface IShape method Volume65 public virtual double Volume()66 {67 return 0;68 }69 70 // implement property Name of IShape71 public virtual string Name72 {73 get74 {75 return "Point3";76 }77 }78 79 } // end class Point3

Implementation of IShape property Name (required), declared virtual to allow deriving classes to override

Page 37: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

373 using System;4 5 // Circle3 inherits from class Point36 public class Circle3 : Point37 {8 private double radius; // Circle3 radius9 10 // default constructor11 public Circle3()12 {13 // implicit call to Point3 constructor occurs here14 }15 16 // constructor17 public Circle3( int xValue, int yValue, double radiusValue )18 : base( xValue, yValue )19 {20 Radius = radiusValue;21 }22 23 // property Radius24 public double Radius25 {26 get27 {28 return radius;29 }30

Page 38: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

3831 set32 {33 // ensure non-negative Radius value34 if ( value >= 0 )35 radius = value;36 }37 }38 40 public double Diameter()41 {42 return Radius * 2;43 }44 45 // calculate Circle3 circumference46 public double Circumference()47 {48 return Math.PI * Diameter();49 }50 51 // calculate Circle3 area52 public override double Area()53 {54 return Math.PI * Math.Pow( Radius, 2 );55 }56 57 // return string representation of Circle3 object58 public override string ToString()59 {60 return "Center = " + base.ToString() +61 "; Radius = " + Radius;62 }63

Page 39: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

3964 // override property Name from class Point365 public override string Name66 {67 get68 {69 return "Circle3";70 }71 }72 73 } // end class Circle3

Page 40: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

403 using System;5 // Cylinder3 inherits from class Circle36 public class Cylinder3 : Circle37 {8 private double height; // Cylinder3 height9 10 // default constructor11 public Cylinder3()12 {13 // implicit call to Circle3 constructor occurs here14 }15 16 // constructor17 public Cylinder3( int xValue, int yValue, double radiusValue,18 double heightValue ) : base( xValue, yValue, radiusValue )19 {20 Height = heightValue;21 }22 23 // property Height24 public double Height25 {26 get27 {28 return height;29 }30

Page 41: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

4131 set32 {33 // ensure non-negative Height value34 if ( value >= 0 )35 height = value;36 }37 }38 39 // calculate Cylinder3 area40 public override double Area()41 {42 return 2 * base.Area() + base.Circumference() * Height;43 }44 45 // calculate Cylinder3 volume46 public override double Volume()47 {48 return base.Area() * Height;49 }50 51 // return string representation of Cylinder3 object52 public override string ToString()53 {54 return "Center = " + base.ToString() +55 "; Height = " + Height;56 }57

Page 42: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

4258 // override property Name from class Circle359 public override string Name60 {61 get62 {63 return "Cylinder3";64 }65 }66 67 } // end class Cylinder3

Page 43: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

435 using System.Windows.Forms;6 7 public class Interfaces2Test8 {9 public static void Main( string[] args )10 {11 // instantiate Point3, Circle3 and Cylinder3 objects12 Point3 point = new Point3( 7, 11 );13 Circle3 circle = new Circle3( 22, 8, 3.5 );14 Cylinder3 cylinder = new Cylinder3( 10, 10, 3.3, 10 );15 16 // create array of IShape references17 IShape[] arrayOfShapes = new IShape[ 3 ];18 19 // arrayOfShapes[ 0 ] references Point3 object20 arrayOfShapes[ 0 ] = point;21 22 // arrayOfShapes[ 1 ] references Circle3 object23 arrayOfShapes[ 1 ] = circle;24 25 // arrayOfShapes[ 2 ] references Cylinder3 object26 arrayOfShapes[ 2 ] = cylinder;27 28 string output = point.Name + ": " + point + "\n" +29 circle.Name + ": " + circle + "\n" +30 cylinder.Name + ": " + cylinder;31

Page 44: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

32 foreach ( IShape shape in arrayOfShapes )33 {34 output += "\n\n" + shape.Name + ":\nArea = " + 35 shape.Area() + "\nVolume = " + shape.Volume();36 }37 38 MessageBox.Show( output, "Demonstrating Polymorphism" );39 }40 }

Page 45: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

ArrayList

• Sample ArrayList code:ArrayList myList = new ArrayList();myList.Add ("DotNetSpider"); // Add a string.myList.Add(1032); // Add an integermyList.Add( DateTime.Now ); // Add current time.myList.Add( new DataTable() ); // Add a datatable

Page 46: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Issues with ArrayList

• How do I get a value out:

object myInt = myList[2];

• How do I get the correct type – cast:

int myInt = (int) myList[2];

Page 47: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Issues with ArrayList

• What if I didn’t want a heterogenous collection of objects, but a nice, say queue, of integers?Queue myQueue = new Queue();myQueue.Put(4);int myInt = (int) myQueue.Get();

• Code littered with casting • What actually happens – boxing!

Create a new box’ed int on the heap.Copy the value 4 into this box’ed int.

Get the box’ed int object.Copy the box’ed value to myInt.

Page 48: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

• User-defined operators• Must be a static method

internal class Car { private string vid; public static bool operator ==(Car x, Car y) { return x.vid == y.vid; }}

Operator Overloading

Page 49: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Operator Overloading

• Overloadable unary operators

+ - ! ~true false ++ --

Overloadable binary operators+ - * / ! ~% & | ^ == !=<< >> < > <= >=

Page 50: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Operator Overloading

• No overloading for member access, method invocation, assignment operators, nor these operators: sizeof, new, is, as, typeof, checked, unchecked, &&, ||, and ?:

• Overloading a binary operator (e.g. *) implicitly overloads the corresponding assignment operator (e.g. *=)

Page 51: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Operator Overloading

public struct Vector { private int x, y; public Vector(int x,int y) { this.x = x; this.y =

y; } public static Vector operator +(Vector a, Vector b) { return new Vector(a.x + b.x, a.y + b.y); } public static Vector operator*(Vector a, int scale) { return new Vector(a.x * scale, a.y * scale); } public static Vector operator*(int scale, Vector a) { return a * scale; }}

Page 52: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

• Can also specify user-defined explicit and implicit conversions

internal class Note { private int value; // Convert to hertz – no loss of precision public static implicit operator double(Note x) { return ...; } // Convert to nearest note public static explicit operator Note(double x) { return ...; }}

Note n = (Note)442.578;double d = n;

Conversion Operators

Page 53: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

The is Operator

• The is operator is used to dynamically test if the run-time type of an object is compatible with a given type

private static void DoSomething(object o) { if (o is Car) ((Car)o).Drive();}

Page 54: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

The as Operator

• The as operator tries to convert a variable to a specified type; if no such conversion is possible the result is null

• More efficient than using is operator– Can test and convert in one operation

private static void DoSomething(object o) { Car c = o as Car; if (c != null) c.Drive();}

Page 55: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

• Consider designing and implementing a set of classes to represent books, library items, and library books.

• a) An abstract class library item contains two pieces of information: a unique ID (string) and a holder (string). The holder is the name of person who has checked out this item. The ID can not change after it is created, but the holder can change.

• b) A book class inherits from library item class. It contains data author and title where neither of which can change once the book is created. The class has a constructor with two parameters author and title, and two methods getAuthor() to return author value and getTitle() to return title value.

• c) A library book class is a book that is also a library item (inheritance). Suggest the required data and method for this class.

• d) A library is a collection of library books (Main class) which has operations: add new library book to the library, check out a library item by specifying its ID, determine the current holder of library book given its ID

Page 56: String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper

Data Abstraction and Information Hiding

• Classes should hide implementation details• Stacks

– Last-in, first-out (LIFO)– Items are pushed onto the top of the stack– Items are popped off the top of the stack

• Queues– Similar to a waiting line– First-in, first-out (FIFO)– Items are enqueued (added to the end)– Items are dequeued (taken off the front)