1 / 52

Lecture 4 Overview of Classes, Containers & Generics

Lecture 4 Overview of Classes, Containers & Generics. What is a Programming Object?.

rupali
Download Presentation

Lecture 4 Overview of Classes, Containers & Generics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 4 Overview of Classes, Containers & Generics

  2. What is a Programming Object? An object is an instance of a class. A class is a template for an object. Everything's an object!!! Statements such as these are not all that helpful when we are struggling to understand the basic concepts of object-oriented programming (OOP). It is better to look as some examples of objects, such as a textbox, a push-button or some user-defined non-GUI object like a cardDeck. Each of these objects has properties that can be accessed and sometimes manipulated. Multiple instances can be defined for them, and there can be different characteristics for each instance. hello there... Start A programming object is a collection of data (variables or literal constants) and a set of functions that operate on the data. Programming objects give us the illusion of material objects and can be used to simplify the task of program design.

  3. Life Cycle of an Object Every object has a clearly defined life cycle. Apart from the normal state of "being in use," this life cycle includes two important stages: Construction: When an object is first instantiated it needs to be initialized. This initializaztion is known as construction and is carried out by a constructor function. Destruction: When an object is destroyed, there are often some clean-up tasks to perform, such as freeing memory. This is the job of a destructor function. Note: The actions of the destructor function may not occur immediately, so we cannot rely on this function to release memory when we need it. Later we will look into the use of disposable objects to help manage critical resources.

  4. Class Members The methods (functions) and data in a class are called class members. Data Members - Data members are instance members unless they are explicitly designated as static. Static data values are associated with the class as a whole. Each instance of a class has its own copy of an instance data value. Data members can be fields, constants, and events. Function Members - Function members perform some operation on the data members of the class. Function members can be methods, properties, constructors, finalizers, operators, and indexers.

  5. Methods Are the standard form for functions and procedures. They may have zero or more arguments, they can be either instance or static, and they may or may not return a data value. public int YetAnother(int val) { // so something with val return//some integer } public void OneMore(ref int val) { // change the value of val } public static void SomeMethod() { // stuff } public static int SomeOther() { return// some integer }

  6. Accessors for Properties & Fields These are sets of functions that can be accessed from the client through dot-notation. Properties can do the same type of things that methods can do, except they have their own syntax (e.g. get and set). public string SomeProperty { get { return// the value of the property } set { //set the property } } public string SomeOtherProperty { get { return// the value } }

  7. Constructors The constructor has the same name as the class and it initializes data or does whatever is needed to be done when a class instance is created. public class TheClassName { public TheClassName { // stuff to do the construction } // other stuff } public class AnExample { public AnExample() { // default constructor stuff } public AnExample(int num) { // constructor stuff that uses num } } CupOfCoffee myCup = new CupOfCoffee( ); CupOfCoffee myCup = new CupOfCoffee("Maxwell House - Original",false,true); CupOfCoffee(string coffeebrand, bool cream, bool sugar)

  8. Finalizers (Destructors) The finalizer has the same name as the class (preceded by a tilde, ~) and it releases data or does whatever is needed to be done when a class instance is disposed. class SampleClass { ~SampleClass() { // destructor stuff } } "Destructors are used by the .NET Framework to clean up after objects. In general, you don't have to provide code for a destructor method; instead, the default operation works for you." We cannot rely on the destructor to free up resources that are used by an object instance, as this may be a long time after the last time the object is used. Instead we can create Disposable Objects.

  9. Operators Operators are infix functions usually defined by one or two symbols. Examples are =, +, >=, &&, and so on. In C# we can overload operators for user-defined data types. public double x,y,z; public Vec_3(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public static Vec_3 operator +(Vec_3 lhs, Vec_3 rhs) { Vec_3 result = new Vec_3(lhs); result.x += rhs.x; result.y += rhs.y; result.z += rhs.z; return result; } public Vec_3(Vec_3 rhs) { x = rhs.x; y = rhs.y; z = rhs.z; }

  10. Indexers Indexers are used like index values to gain access into an array, except that they can refer to an object. Instead of creating a name, you use the this keyword, which refers the the current object. publicsomedatatypethis[int index] { get { // do something return some_value; } set { //set a value in the class related to index } }

  11. Inheritance There are two types of inheritance, implementation and interface. We will review implementation inheritance first, since it is the more common form of inheritance. In implementation inheritance, a type derives from a base type, taking all the base type's member fields and functions. class ExampleClass : object { // stuff } class ExampleClass { // same stuff } these are the same

  12. Virtual Methods Declaring a method as virtual allows it to be overidden by any class that is derived from the defining class. Virtual members cannot be private, as this would cause a paradox -- a member cannot be overridden by a derived class and yet be inaccessible from the derived class. class SomeBaseClass { public vitual void SomeVirtualMethod() { // method stuff } }

  13. Overridding a Virtual Method in a Derived Class class BaseGraphicsClass { public virtual void DrawLine() { } public virtual void DrawPoint() { } } class NewDerivedClass : BaseGraphicsClass { public override void DrawPoint() { } } Instances of NewDerivedClass have access to the DrawLine() method as well as the new version of the DrawPoint() method.

  14. OOP in Wndows Applications

  15. There is no Magic namespace ButtonMakerDemo { publicpartialclassForm1 : Form { public Form1() { InitializeComponent(); } privatevoid newButton_Click(Object sender, System.EventArgs e) { ((Button) sender).Text = "Clicked!!"; } privatevoid button1_Click(object sender, EventArgs e) { ((Button)sender).Text = "Clicked!"; Button newButton = newButton(); newButton.Click += newEventHandler(newButton_Click); Controls.Add(newButton); } } }

  16. Classes and Interfaces Demo namespaceClassInterfaceDemo { publicabstractclassMyBase { } internalclassMyClass : MyBase { } publicinterfaceIMyBaseInterface { } publicinterfaceIMyBaseInterface2 { } internalinterfaceIMyInterface : IMyBaseInterface, IMyBaseInterface2 { } internalsealedclassMyComplexClass : MyClass, IMyInterface { } classProgram { staticvoid Main(string[] args) { MyComplexClass myObj = newMyComplexClass(); Console.WriteLine(myObj.ToString()); Console.ReadKey(); } } }

  17. The Class Diagram

  18. System.Object Methods

  19. Collections

  20. Main Program (Animal Array) Console.WriteLine("Create an Array type collection of Animal " + "objects and use it:"); Animal[] animalArray = newAnimal[2]; Cow myCow1 = newCow("Deirdre"); animalArray[0] = myCow1; animalArray[1] = newChicken("Ken"); foreach (Animal myAnimal in animalArray) { Console.WriteLine("New {0} object added to Array collection, " + "Name = {1}", myAnimal.ToString(), myAnimal.Name); } Console.WriteLine("Array collection contains {0} objects.", animalArray.Length); animalArray[0].Feed(); ((Chicken)animalArray[1]).LayEgg(); Console.WriteLine();

  21. Main Program (Animal ArrayList Collection) Console.WriteLine("Create an ArrayList type collection of Animal " + "objects and use it:"); ArrayList animalArrayList = newArrayList(); Cow myCow2 = newCow("Hayley"); animalArrayList.Add(myCow2); animalArrayList.Add(newChicken("Roy")); foreach (Animal myAnimal in animalArrayList) { Console.WriteLine("New {0} object added to ArrayList collection," + " Name = {1}", myAnimal.ToString(), myAnimal.Name); } Console.WriteLine("ArrayList collection contains {0} objects.", animalArrayList.Count); ((Animal)animalArrayList[0]).Feed(); ((Chicken)animalArrayList[1]).LayEgg(); Console.WriteLine(); Console.WriteLine("Additional manipulation of ArrayList:"); animalArrayList.RemoveAt(0); ((Animal)animalArrayList[0]).Feed(); animalArrayList.AddRange(animalArray); ((Chicken)animalArrayList[2]).LayEgg(); Console.WriteLine("The animal called {0} is at index {1}.", myCow1.Name, animalArrayList.IndexOf(myCow1)); myCow1.Name = "Janice"; Console.WriteLine("The animal is now called {0}.", ((Animal)animalArrayList[1]).Name);

  22. Limitations of Arrays

  23. ArrayList Collection

  24. The foreach Construct

  25. Ienumerable is Implicit in foreach

  26. C# Iterators – alternative definition • Iterators in the .NET Framework are called "enumerators" and represented by the IEnumerator interface. IEnumerator provides a MoveNext() method, which advances to the next element and indicates whether the end of the collection has been reached; a Current property, to obtain the value of the element currently being pointed at; and an optional Reset() method, to rewind the enumerator back to its initial position. The enumerator initially points to a special value before the first element, so a call to MoveNext() is required to begin iterating. • Enumerators are typically obtained by calling the GetEnumerator() method of an object implementing the IEnumerable interface. Container classes typically implement this interface. However, the foreach statement in C# can operate on any object providing such a method, even if it doesn't implement IEnumerable. Both interfaces were expanded into generic versions in .NET. • The following shows a simple use of iterators in C# : • // explicit version • IEnumerator<MyType> iter = list.GetEnumerator(); • while (iter.MoveNext()) • Console.WriteLine(iter.Current); • // implicit version • foreach (MyType value in list) • Console.WriteLine(value); http://en.wikipedia.org/wiki/Iterator

  27. The Length & Count Properties

  28. Collections Accessibility

  29. Other Useful Methods in Collections Class

  30. AddRange( )

  31. IndexOf( )

  32. The Generic List<T> loading data from a file using System.IO; : : namespace EmpListDemo { staticclassProgram { staticvoid Main(string[] args) { string fname = "empstable.txt"; string txtline; List<Employee> Emps = newList<Employee>(); // a generic list of Employee List<Employee> Emps2 = newList<Employee>(); // we will make a copy of Emps // reading employee data from a text file TextReader tr = newStreamReader(fname); do { txtline = tr.ReadLine(); if (txtline == "xxx") break; string[] field = txtline.Split(','); Emps.Add(newEmployee(field[0].Trim(),field[1].Trim(), Convert.ToInt32(field[2]), Convert.ToInt32(field[3]), Convert.ToDouble(field[4]))); } while (true); tr.Close(); : :

  33. Displaying the Contents of the List Emps // display the contents of the list Emps foreach (Employee emp in Emps) { Console.WriteLine("{0} {1} {2} {3} {4}", emp.FirstName, emp.LastName, emp.Age, emp.YrsEmp, emp.Wage); } Wade Boggs 45 20 12.5 Robin Banks 32 13 9.5 Jerry Mander 27 6 8.1 Amanda Rekonwith 55 25 22.5 Doug Wells 38 10 25.05 Anita Break 23 2 7.5 Juan Abrew 48 7 32.2 Ben Dover 37 9 24.15 Ilene Dover 28 1 22.9

  34. Making a Copy of a List // we are making a copy of Emps called Emps2 foreach (Employee emp in Emps) { Employee emp2 = newEmployee(); emp2 = emp; Emps2.Add(emp2); } // so why not just assign one list to the other? // Emps2 = Emps; // // because this would not make a separate copy but // rather point both Emps2 and Emps to the same records!

  35. The RemoveAll Delegate Method // we "tag" each record that passes our criteria foreach (Employee emp in Emps2) { if (emp.Age > 39 & emp.YrsEmp >= 10) emp.Tag = true; } // now we remove all records from Emps2 that HAVE NOT // been "tagged" i.e. remove those with emp.Tag = false // this construct is implemented using a delegate Emps2.RemoveAll(delegate(Employee emp) { return !emp.Tag; }); Wade Boggs 45 20 12.5 Robin Banks 32 13 9.5 Jerry Mander 27 6 8.1 Amanda Rekonwith 55 25 22.5 Doug Wells 38 10 25.05 Anita Break 23 2 7.5 Juan Abrew 48 7 32.2 Ben Dover 37 9 24.15 Ilene Dover 28 1 22.9 age>39 and yrsemp >= 10 Wade Boggs 45 20 12.5 Amanda Rekonwith 55 25 22.5

  36. Working with LINQ // this is a LINQ query! var queryresults = from q in Emps where q.LastName.StartsWith("B") select q; // so what's in queryresults??? // let's take a look Console.WriteLine(); foreach (var q in queryresults) { Console.WriteLine(q.FirstName + " " + q.LastName); } Wade Boggs 45 20 12.5 Robin Banks 32 13 9.5 Jerry Mander 27 6 8.1 Amanda Rekonwith 55 25 22.5 Doug Wells 38 10 25.05 Anita Break 23 2 7.5 Juan Abrew 48 7 32.2 Ben Dover 37 9 24.15 Ilene Dover 28 1 22.9 Wade Boggs Robin Banks Anita Break

  37. Another LINQ Query Example // let's try another example // notice we don't redefine the var queryresults queryresults = from q in Emps where q.Age>30 select q; // now what's in queryresults??? Console.WriteLine(); foreach (var q in queryresults) { Console.WriteLine(q.FirstName + " " + q.LastName); } Console.ReadKey(); Wade Boggs 45 20 12.5 Robin Banks 32 13 9.5 Jerry Mander 27 6 8.1 Amanda Rekonwith 55 25 22.5 Doug Wells 38 10 25.05 Anita Break 23 2 7.5 Juan Abrew 48 7 32.2 Ben Dover 37 9 24.15 Ilene Dover 28 1 22.9 Wade Boggs Robin Banks Amanda Rekonwith Doug Wells Juan Abrew Ben Dover

  38. // one more example queryresults = from q in Emps where ((q.Age>40 & q.Wage<20.0) | (q.Age<40 & q.Wage>25.0)) select q; Wade Boggs 45 20 12.5 Robin Banks 32 13 9.5 Jerry Mander 27 6 8.1 Amanda Rekonwith 55 25 22.5 Doug Wells 38 10 25.05 Anita Break 23 2 7.5 Juan Abrew 48 7 32.2 Ben Dover 37 9 24.15 Ilene Dover 28 1 22.9 Wade Boggs Doug Wells

  39. Loading an Array from a Text File using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; namespace LoadArrayFromTextfile { classProgram { staticvoid Main(string[] args) { int[,] mat = newint[10,10]; string textline; int k; TextReader tr = newStreamReader("sample_01.txt"); for (int i = 0; i < 10; i++) { textline = tr.ReadLine(); k = 0; foreach (string str in textline.Split(' ')) { if (str != "") { mat[i, k] = Convert.ToInt32(str); k += 1; } } } tr.Close(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { Console.Write("{0} ", mat[i, j]); } Console.WriteLine(); } Console.ReadKey(); } } } 5 6 4 3 2 7 7 8 6 5 4 3 2 5 3 2 3 8 8 8 1 1 2 2 3 3 6 4 5 3 3 5 5 6 4 9 7 5 2 0 4 3 8 7 0 4 3 2 5 4 1 3 2 4 3 5 4 6 5 7 7 5 6 8 7 7 5 4 7 9 1 3 2 4 3 6 5 4 3 2 8 8 9 6 5 5 3 0 0 1 1 1 1 6 6 8 8 7 6 5

  40. Reading and Writing Textfiles List<Employee> Emps = newList<Employee>(); string txtline; TextReader tr = newStreamReader("employees.txt"); do { txtline = tr.ReadLine(); if (txtline == "xxx") break; string[] field = txtline.Split('\t'); Emps.Add(newEmployee(field[0].Trim(), field[1].Trim(), Convert.ToInt32(field[2]), Convert.ToInt32(field[3]), Convert.ToDouble(field[4]))); } while (true); tr.Close();

  41. Reading and Writing Text Files continued foreach (Employee emp in Emps) { Console.WriteLine("{0} {1}", emp.FirstName, emp.LastName); } TextWriter tw = newStreamWriter("employees.txt"); foreach (Employee emp in Emps) { tw.WriteLine("{0} \t {1} \t {2} \t {3} \t {4}", emp.FirstName, emp.LastName, emp.Age, emp.YrsEmp, emp.Wage); } tw.WriteLine("xxx"); tw.Close();

  42. Dealing with Data cut & paste

  43. Pasting into Word or PPT Preserves Cells

  44. Pasting to a Text Editor Creates Separators e.g. Tabs

More Related