classes methods and properties. introduction to classes and objects in object-oriented programming...

35
Classes Methods and Properties

Upload: buck-valentine-johnson

Post on 06-Jan-2018

247 views

Category:

Documents


0 download

DESCRIPTION

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

TRANSCRIPT

Page 1: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

ClassesMethods and Properties

Page 2: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Introduction to Classes and ObjectsIn object-oriented programming terminology, a class is defined

as a kind of programmer-defined typeFrom the natural language definition of the word “class”:

Collection of members that share certain attributes and functionalityLikewise 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)

Page 3: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

// GradeBook.cs// Class declaration with one method.using System;

public class GradeBook { // display a welcome message to the GradeBook user public void DisplayMessage() { Console.WriteLine( "Welcome to the Grade Book!" ); } // end method DisplayMessage} // end class GradeBook

Let’s create this class using Visual Studio 2012

Class declaration

classkeyword

name of the class

name of the method

access modifiers

Page 4: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

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 = new GradeBook();

// display welcome message myGradeBook . DisplayMessage(); }} // end class GradeBookTest

How to use Classes

Page 5: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

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

Page 6: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

How to access data of an object ?

// create a GradeBook object and assign it to myGradeBookGradeBook 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

Page 7: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Propertiespublic 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

Page 8: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Access data of objects via Properties

// create a GradeBook object and assign it to myGradeBookGradeBook myGradeBook = new GradeBook();myGradeBook.CourseName = “IT528”;

Now it builds fine.

Page 9: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Autoimplemented Propertiespublic 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

Page 10: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

MethodsThe best way to develop and maintain a large application is to

construct it from small, simple pieces divide and conquerMethods 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:

Page 11: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Methods and ClassesThe behavior of a class is defined by its methods and

properties by which objects of that class are manipulatedYou should know about the public methods and what they do

name of the methodparameters and parameter typesreturn typefunctionality

You don’t need to know how the method is implemented or how the property is storedanalogy: you can add two int variables using +, but you don’t

need to know how computer really adds

Page 12: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Methods syntax access_modifier return_type func_name(parameter list) {statement_1;…statement_n;return return_type;

}(type param1, type2 param2, …, type paramn)

public, private

Examples: public void DisplayMessage () public GradeBook (string name) public static void Main (string[] args)

Page 13: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

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.

Page 14: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Method Overloadingvoid 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 errorint SquareRoot(int num);double SquareRoot (int num);

Page 15: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Scope of VariablesThe 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

Page 16: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

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

…}

Page 17: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

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 myGradeBookGradeBook myGradeBook = new GradeBook(Console.ReadLine());

@myGradeBook courseName

GradeBook

• The new operator calls the class’s constructor to perform the initialization.• The compiler provides a public default constructor with no parameters, so every class has a constructor.

• GradeBook is a reference type as all classes

Page 18: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Copy constructor// constructorpublic GradeBook(GradeBook inputGradeBook){ CourseName = inputGradeBook.CourseName;

}

Page 19: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Access modifierspublic

Methods and Constructors as seen by programmerProgrammer can use the methods and properties defined in the

public section onlyprivate

Mostly the data part of the class Necessary for internal implementation of classNot accessible by programmer

protectedwe will see this in inheritance

internalAccessible only by methods in the defining assemblyExample: modify HelloWorldLibrary SayHello method to be internal

protected internalwe will see this in inheritance

Page 20: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

ExampleAccount classLet’s use Class View of Visual Studio hereAlso look at Object Browser for Math class

The Object Browser lists all classes of the Framework Class Library.

Page 21: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

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

Page 22: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Overloaded Constructors & thispublic 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 }

Page 23: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

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

Page 24: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

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

Page 25: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Static Methodspublic 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

Page 26: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Math class example (maximum3.sln)Let’s write a method that finds the maximum of 3 numbers

Randomly generate the numbersThen let’s use the Math class to do the same thing

Page 27: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Pass by Reference ParametersThe parameters we have seen so far are value parameters

their arguments are passed by valueif 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.

Page 28: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Pass by Reference (ref & out)

Pass by reference:ref

Need to assign an initial value to the parameterout

No need to assign an initial value to the parameter

static void FunctionOutRef(ref int c, out int d){ d = c + 1; c = c + 1;

}static void Main(string[] args){int num3 = 5, num4;FunctionOutRef(ref num3, out num4);

}

Page 29: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Underlying MechanismsFor value parameters, the arguments’ values are copied

into parametersarguments and parameters have different memory

locations

double Average (int a, int b)

Average(num1, num2)

10 15

10 15

copy value copy value

main function

Page 30: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Underlying MechanismsFor reference parameters, the parameter and the

argument share the same memory locationparameter is an alias of argument

double average (ref int a, int b)

average(ref num1, num2)10

15

15

refers to the same memory location

copy value

main function

Page 31: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Example: SwapWrite a function that swaps the values of its two integer

parameters

Page 32: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

Example: Swapvoid 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 5swap(ref a, ref 5); // syntax error, arguments must be

variables

Page 33: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

constSometimes very useful

provides self documentationre-use the same value across the class or programavoid accidental value changes

Like variables, but their value is assigned at declaration and can never change afterwardsdeclared 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 valueConsole.WriteLine(MathClass.PI * 4 * 4);

but cannot change their valueMathClass.PI = 3.14; causes a syntax error

Page 34: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

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

Page 35: Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined

readonlyconst is set at compile timereadonly is set at runtimereadonly can be used for reference types as wellConstructor can set readonly fields but not any

other methodspublic class GradeBook{ private readonly string courseName = “”;

public GradeBook(string name) { courseName = name; }}