1 / 35

Classes Methods and Properties

Classes Methods and Properties. Introduction to Classes and Objects. In object-oriented programming terminology, a class is defined as a kind of programmer-defined type From the natural language definition of the word “class”:

bolander
Télécharger la présentation

Classes Methods and Properties

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. ClassesMethods and Properties

  2. Introduction to Classes and Objects • In object-oriented programming terminology, a class is defined as a kind of programmer-defined type • From the natural language definition of the word “class”: • Collection of members that share certain attributes and functionality • Likewise classes in object-oriented programming • In object oriented programming languages (like C#, Java) classes are used to combine everything for a concept (like date) • Data (state / attributes) (e.g. date day, month, year) • Methods (behavior / tasks)(e.g. display date, increment date)

  3. Class declaration // GradeBook.cs // Class declaration with one method. using System; public class GradeBook { // display a welcome message to the GradeBook user publicvoid DisplayMessage() { Console.WriteLine( "Welcome to the Grade Book!" ); } // end method DisplayMessage } // end class GradeBook • Let’s create this class using Visual Studio 2012 class keyword name of the class name of the method access modifiers

  4. How to use Classes • In other words create instances of classes  objects // Create and manipulate a GradeBook object. using System; public class GradeBookTest { public static void Main(string[] args) { // create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = newGradeBook(); // display welcome message myGradeBook . DisplayMessage(); } } // end class GradeBookTest

  5. Member data (field / instance variable) public class GradeBook { private string courseName; // course name for this GradeBook // display a welcome message to the GradeBook user public void DisplayMessage() { // use member field courseName to get the // name of the course that this GradeBook represents Console.WriteLine( "Welcome to the grade book for\n{0}!", courseName ); // display property CourseName } // end method DisplayMessage } // end class GradeBook

  6. How to access data of an object ? // create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = new GradeBook(); myGradeBook.courseName = “IT528”; • Would the above code build? • Hiding data: why? • you can drive cars, but you don’t need to know how the fuel injection works • when the car’s fuel injection changes, you can still drive that new car

  7. Properties public class GradeBook { // course name for this GradeBook private string courseName; // property to get and set the course name public string CourseName { get { return courseName; } // end get set { courseName = value; } // end set } // end property CourseName

  8. Access data of objects via Properties // create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = new GradeBook(); myGradeBook.CourseName = “IT528”; • Now it builds fine.

  9. Autoimplemented Properties public class GradeBook { // auto-implemented property CourseName implicitly creates an // instance variable for this GradeBook's course name public string CourseName { get; set; } // constructor initializes auto-implemented property CourseName public GradeBook( string name ) { CourseName = name; // set CourseName to name } public void DisplayMessage() { // use auto-implemented property CourseName to get the // name of the course that this GradeBook represents Console.WriteLine( "Welcome to the grade book for\n{0}!", CourseName); } } // end class GradeBook

  10. Methods • The best way to develop and maintain a large application is to construct it from small, simple pieces  divide and conquer • Methods allow you to modularize an application by separating its tasks into reusable units. • Reuse the Framework Library, do not reinvent the wheel • Divide your application into meaningful methods such that it is easier to debug and maintain. • Methods == Worker analogy:

  11. Methods and Classes • The behavior of a class is defined by its methods and properties by which objects of that class are manipulated • You should know about the public methods and what they do • name of the method • parameters and parameter types • return type • functionality • You don’t need to know how the method is implemented or how the property is stored • analogy: you can add two int variables using +, but you don’t need to know how computer really adds

  12. Methods syntax access_modifierreturn_typefunc_name(parameter list) { statement_1; … statement_n; return return_type; } (type param1, type2 param2, …, type paramn) public, private Examples: • publicvoidDisplayMessage () • publicGradeBook (string name) • public static voidMain (string[] args)

  13. Methods syntax (cont’d) • There are three ways to return control to the statement that calls a method. • Reaching the end of the method. • A return statement without a value. • A return statement with a value. • There could be more than one return in a method. • At least one return is required in a non-void method.

  14. Method Overloading void DoSomething(int num1, int num2); void DoSomething(int num1, int num2, int num3); void DoSomething(float num1, float num2); void DoSomething(double num1, double num2); • The compiler distinguishes overloaded methods by their signature—a combination of the method’s name and the number, types and order of its parameters. • Method calls cannot be distinguished by return type  compile error intSquareRoot(int num); double SquareRoot (int num);

  15. Scope of Variables • The basic scope rules are as follows: • The scope of a parameter declaration is the body of the method in which the declaration appears. • The scope of a local-variable declaration is from the point at which the declaration appears to the end of the block containing the declaration. • The scope of a non-static method, property or field of a class is the entire body of the class. • If a local variable or parameter in a method has the same name as a field, the field is hidden until the block terminates • Let’s see an example: scope.cs

  16. Constructor • Special method to create objects and initialize its data members • A constructor must have the same name as its class. • There might be several constructors with same name, but different parameters public class GradeBook { // course name for this GradeBook private string courseName; // constructor public GradeBook(string name) { courseName = name; } // default constructor public GradeBook() { courseName = “IT 528”; } … }

  17. How to use Constructor // prompt for and read course name Console.WriteLine("Please enter the course name:"); // create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = new GradeBook(Console.ReadLine()); GradeBook @ myGradeBook courseName • The new operator calls the class’s constructor to perform the initialization. • The compiler provides a publicdefault constructor with no parameters, so every class has a constructor. • GradeBook is a reference type as all classes

  18. Copy constructor // constructor public GradeBook(GradeBook inputGradeBook) { CourseName = inputGradeBook.CourseName; }

  19. Access modifiers • public • Methods and Constructors as seen by programmer • Programmer can use the methods and properties defined in the public section only • private • Mostly the data part of the class • Necessary for internal implementation of class • Not accessible by programmer • protected • we will see this in inheritance • internal • Accessible only by methods in the defining assembly • Example: modify HelloWorldLibrarySayHello method to be internal • protected internal • we will see this in inheritance

  20. Example • Account class • Let’s use Class View of Visual Studio here • Also look at Object Browser for Math class • The ObjectBrowser lists all classes of the Framework Class Library.

  21. this public class SimpleTime { private int hour; // 0-23 private int minute; // 0-59 private int second; // 0-59 // if the constructor uses parameter names identical to // instance variable names the "this" reference is // required to distinguish between names public SimpleTime( int hour, int minute, int second ) { this.hour = hour; // set "this" object's hour // instance variable this.minute = minute; // set "this" object's minute this.second = second; // set "this" object's second }

  22. Overloaded Constructors & this public class Time2 { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 // Time2 no-argument constructor public Time2() : this( 0, 0, 0 ) { } // Time2 constructor: hour supplied, minute & second defaulted to 0 public Time2( int h ) : this( h, 0, 0 ) { } // Time2 constructor: hour & minute supplied, second defaulted to 0 public Time2( int h, int m ) : this( h, m, 0 ) { } // Time2 constructor: hour, minute and second supplied public Time2( int h, int m, int s ) { SetTime( h, m, s ); // invoke SetTime to validate time }

  23. Object Initalizers static void Main( string[] args ) { // create a Time object and initialize its properties Time aTime = new Time { Hour = 14, Minute = 145, Second = 12 }; … } • The class name is immediately followed by an object-initializer list—a comma-separated list in curly braces ({}) of properties and their values. • Each property name can appear only once in the object-initializer list. • The object-initializer list cannot be empty. • The object initializer executes the property initializers in the order in which they appear. • An object initializer first calls the class’s constructor, so any values not specified in the object initializer list are given their values by the constructor.

  24. Destructors • A destructor’s name is the class name, preceded by a tilde, and it has no access modifier in its header. public class GradeBook { // constructor public GradeBook(string name) { courseName = name; } // destructor ~GradeBook() { } } • The destructor is invoked by the garbage collector to perform termination housekeeping before its memory is reclaimed. • Many FCL classes provide Close or Dispose methods for cleanup.

  25. Static Methods public class GradeBookTest { public static void Main(string[] args) … } public static class Math { … public static int Max(int val1, int val2); public static int Min(int val1, int val2); … } • You do not need to create an object in memory to use the method, you simply use the class’s name to call the method • Other methods of the class cannot be called from a static method, only static methods can be called from other static methods

  26. Math class example (maximum3.sln) • Let’s write a method that finds the maximum of 3 numbers • Randomly generate the numbers • Then let’s use the Math class to do the same thing

  27. Pass by Reference Parameters • The parameters we have seen so far are value parameters • their arguments are passed by value • if you change the value of a parameter in function, corresponding argument does NOT change in the caller function • Let’s see an example: PassByRef.cs.

  28. Pass by Reference (ref & out) • Pass by reference: • ref • Need to assign an initial value to the parameter • out • No need to assign an initial value to the parameter static void FunctionOutRef(refint c, outint d) { d = c + 1; c = c + 1; } static void Main(string[] args) { int num3 = 5, num4; FunctionOutRef(ref num3, out num4); }

  29. Underlying Mechanisms • For value parameters, the arguments’ values are copied into parameters • arguments and parameters have different memory locations double Average (int a, int b) Average(num1, num2) 10 15 copy value copy value main function 10 15

  30. Underlying Mechanisms • For reference parameters, the parameter and the argument share the same memory location • parameter is an alias of argument double average (refint a, int b) average(ref num1, num2) 15 refers to the same memory location copy value main function 10 15

  31. Example: Swap • Write a function that swaps the values of its two integer parameters

  32. Example: Swap void swap(ref int a, ref int b) { int temp; temp = a; a = b; b = temp; } • How do we use this in main? int a=5, b=8; swap(ref a, ref b); // a becomes 8, b becomes 5 swap(ref a, ref 5); // syntax error, arguments must be variables

  33. const • Sometimes very useful • provides self documentation • re-use the same value across the class or program • avoid accidental value changes • Like variables, but their value is assigned at declaration and can never change afterwards • declared by using const before the type name (any type is OK) public const double PI = 3.14159; const int LENGTH = 6; • later you can use their value Console.WriteLine(MathClass.PI * 4 * 4); • but cannot change their value MathClass.PI = 3.14;causes a syntax error

  34. const • Cannot use const with reference types. • Exception: string public const string CLASSNAME = “IT 528”;

  35. readonly • const is set at compile time • readonly is set at runtime • readonly can be used for reference types as well • Constructor can set readonly fields but not any other methods public class GradeBook { private readonly string courseName = “”; public GradeBook(string name) { courseName = name; } }

More Related