• No results found

2.01 Objects, Properties and Instance Variables (1).pptx

N/A
N/A
Protected

Academic year: 2020

Share "2.01 Objects, Properties and Instance Variables (1).pptx"

Copied!
44
0
0

Loading.... (view fulltext now)

Full text

(1)

Objects,

Properties and

Instance Variables

(2)

Purpose

This presentation describes objects, properties and

(3)

Objects—Definition

Objects are self-contained entities that define a set of data and behaviors

Just as there are objects in the real world that have state and behavior, there are objects in the programming world. Example:

Dog object

• State: Breed, Weight, Gender, Color

(4)

Objects—The Basics

Objects in computer programming are defined using

classes

A

Class

is a template from which individual objects

are created.

The states of objects are defined using

Instance

Variable

or

fields

Object behavior is defined using

Methods

(5)

Objects and Instance Variables

• Think of an object’s state, or instance variables as the basic data needed by the program to identify and use the object.

• Example: If the object were a patient at a hospital, some of the essential data needed by a program would be

• Something that identifies the patient from any other patient, or an ID

• Basic data needed to help communicate with the patient: name, address, age, gender, marital status, children or next of kind

• Medical information needed to treat the patient: allergies, existing conditions or ailments, medications currently in use

(6)

Example of Instance

Variables for the Patient

Class

Instance variables are

declared at the class level

Are declared with the private public access modifier

Use camelCase in the identifier

Can be declared on one line or many

using System ; class Patient {

private int id;

private string name; private string address; private double weight; private string gender; private double height; // class implementation code

(7)

Instance Variables—You Decide

List instance variables you might write for a class that defines a rectangle object:

Hint: only use the basic data. Don’t include other data that can be calculated from the basics.

(8)

Writing Identifiers for Instance

Variables

Always use camelCase

Use descriptive words

Favor length over brevity

Bad Examples: Better Examples:

(9)

Properties in C#

A property is a block of code that allows you to access a class data field in a safe and flexible way.

Properties are like the data members of a class, but contain code like the methods

(10)

Properties in C#

Properties have two

assessors

.

Assessors allow users to read or write to a data

member

The Get assessor returns the property value

(11)

Properties in C#

class Student {

private String name; //the field public String Name // the property { get { return name; } set { name= value; } }

Examples of Properties

in C#

Each private field has

a associated public

property to allow

access to its values

Header syntax:

Public Data+Type+Name of field

Name of property is

capitalized

(12)

Why Properties

Properties allow programmers to access and change the values of private instance variables.

Other programmers do not have access to the fields

themselves, but have access to the methods that get the values assigned to them or change the values assigned to them

(13)

The

get

and

set

Properties

The get property allows programmers to access the value assigned to a field.

• The get property always uses the keyword return in its body to return the value of the field to the calling method

The set property allows programmers to change the value assigned to a field.

• The set property always assigned a field to a value

(14)

Using Properties

class Program {

static void Main(string[] args) {

Student stu1 = new Student(); stu1.Name = "Lauren Campbell"; stu1.Gpa = 3.50;

Console.WriteLine("Student Name:" + stu1.Name + ", Student GPA: "+ stu1.Gpa); Console.ReadKey();

} }

Console Output:

Student Name: Lauren Campbell

(15)

Auto-Implemented Properties

A fairly new shortcut to c# (version 3.0 and later) allows programmers a simpler way to set field properties.

Auto-Implemented properties are in-line with the field declarations at the top of the class

(16)

An Example of Auto-Implemented

Property

Notice when using

auto-implemented properties, the public access modifier is used

Notice there is no closing semi-colon outside the curly brackets

public Name { get { return name; } set {

name = value; }

}

public string name

{get; set;}

The block of code to the right and the one above are

(17)

Properties in C#

class Student { public string firstName{get; set;} public string lastName{get; set;}

public string id{get; set;}

public double gpa{get; set;} public string stuClass{get; set;} }

Examples of

Properties

in C#

C# will

automatically

create a private

(18)

Properties Summary

Properties are easy to write and access in C#

When using the public access modifier for instance

variables with properties, C# will automatically create a private instance variable in the background.

(19)

Objects and Behaviors

Behaviors for objects are defined by methods. For the

patient example some behaviors that would be required by a program that dealt with patients include

• Patient visit—patient visits clinic

• Patient Diagnosis—patient is given a diagnosis during a visit to the clinic

• Prescription—patient is given and takes a course of prescribed medication

(20)

Object Use

Any instance of a class can use the dot operator to

call any public method in its class.

object

dot op

erato

r Me

thod b

eing

called

(21)

Methods

namespace RectangleProgram {

class Rectangle {

public double length { get; set; } public double width { get; set; }

public double GetArea( ) {

return this.length * this.width; }

}

The Rectangle class has

one method.

Notice the method

header syntax:

Access modifier return type

(22)

Methods—Access Modifiers

public double getArea( )

{

return this.length * this.width;

} Access modifier: public

A method can be

1)public—the method can be used outside the class but within the namespace

2)Private—the method can only be used within the class

Access modifier return type

(23)

Methods—Return Type

public double GetArea( )

{

return this.length * this.width;

}

Return type: double

A method will either

1)Return nothing to the

calling statement (return type is then void)

2)Return a data type or object to the calling

statement. In this case a double value will be

returned

Access modifier return type

(24)

Methods

public double GetArea( )

{

return this.length * this.width;

}

Identifier Rules

Create identifiers that

1) Use Pascal case for public method identifiers

2) Use descriptive identifiers that clarify code

3) Favor readability over brevity 4) Do not use non-alphabetic

characters

5) Do not use Hungarian notation in C#

6) Do not use keywords in C# and try to avoid keywords from other languages as well

Access modifier return type

identifier( )

(25)

Methods

For every program, there must be a main method

The main method tells the program where to begin executing code

Other methods are provided by the makers of C# such as WriteLine and ReadLine

(26)

Methods

Why write methods?

Programmers could simply place all code in the Main method, so why break codes up into separate methods?

Methods allow code to be reused where needed

(27)

using System ;

class MethodDemo {

static void DoIt ( ) {

Console.WriteLine ("Hello"); }

public static void Main ( ) {

DoIt(); DoIt(); }

}

Example of a silly method

You can see that the code in the method block DoIt can be used repeatedly by simply calling the code in the main method.

Console Output:

Hello Hello

(28)

Method

Parameters

Parameters allow

programmers to pass

values to a method when it is called.

Methods use the values in the execution of their code

What would the output be?

using System ;

class MethodDemo {

static void Silly ( int i) {

Console.WriteLine ( "i is : " + i ) ; }

public static void Main ( ) {

Silly ( 101 ) ; Silly ( 500 ) ; }

(29)

Return Values

• Methods can return a value to the calling method

• In this code, notice the method header return type in bold, which has changed from void (returning nothing) to int.

• Also note the call to the method, which is replaced by the value return when executed.

• What would be the output?

using System ;

class MethodDemo {

static int SillyReturnPlus ( int i) {

i = i + 1;

Console.WriteLine ( "i is : " + i ) ; return i;

}

public static void Main ( ) {

int res;

res = SillyReturnPlus (5);

Console.WriteLine ( "res is : " + res ) ; }

(30)

Method Passing—by Value

Passing by Value

When a primitive is passed to a method, it is passed by value.

Passing by Value is a one-way street.

The value goes to the method being called and stays within that method.

The scope of the value passed is the method that receives it.

(31)

Passing by

Value

Consider the following code

Walk through the code and see if you can

determine how test is treated in memory

What would be the output?

Class Program {

static void AddOneToParam(int i) {

i = i + 1;

Console.WriteLine("i is : " + i); }

static void Main(string[] args) {

int test = 20;

AddOneToParam(test);

Console.WriteLine("test is : " + test); Console.ReadKey();

(32)

Passing by Value

Main

ThisMethod

(6);

static void

ThisMethod(int i) {

i = i + 5 }

test = 6 i = 0

int test =

6 i = 6

i = 11

(33)

Passing by Reference

C# provides a way to pass a value as a reference

Instead of passing something like 6 to the method, it instead passes something like memory location 4503.

(34)

Passing by Reference

Main

ThisMethod(

6);

static void

ThisMethod(ref int i) {

i = i + 5 }

Test =

6 i = 6

i = 11

6 i =

11

Test and i variables are pointing to the same place in memory where the

value assigned to the variables exists.

If one variable changes, the other must change

because they are pointing to the same memory

(35)

namespace RectangleProgram {

class Rectangle {

public double length { get; set; } public double width { get; set; }

public Rectangle(double lgth, double wdth)

{

length = lgth; width = wdth; }

public double GetArea() {

return this.length * this.width; }

} }

The Rectangle Program

Rectangle Class

Properties or instance

variables—define the object’s state

Constructor—special method used to create an object

(36)

Object Creation

Objects must be created in a program before they

can be used. This process involves three steps:

1.

Declaration—Variable Type and Name

2.

Instantiation—The keyword

new

is used to

create the object

3.

Initialization—The keyword

new

is followed by a

call to a constructor, which initializes the

(37)

A Rectangle Object Instantiation

This is an example of an instantiation of a

Rectangle object, using the Rectangle class.

Rectangle rec1;

rect1 =

new

Rectangle

(10, 20);

Declaration of the variable using a data type and identifier

Declaratin o

Instantiati on

Instantiation of rec1 using the keyword

new

Call to a c

onstructor that assigns

(38)

Instantiation

When an object has been instantiated, it is said to be an instance of that class.

stu1 is an instance of the Student class

The same class can be used to instantiate many different instances, each having it’s own state, but sharing the

(39)

Object Use

Once an object has been instantiated, it has access to all of the fields or instance variables and methods of the class or struct from which it was created.

This means it can call any public method in its class

(40)

Practice Creating Objects

namespace library {

public class Book {

private String author; private String title;

private String deweyNum;

public Book(String ttl) {

title = ttl; }

} }

Try your hand at

instantiating a book object using this Book class.

Declaration:

Class Name + Identifier Initialization:

(41)

Practice Creating Objects

namespace AsteroidBang {

public class Asteroid {

private double length; private double width; private double speed;

public Asteroid(double spd, double lgth, double wdth) {

speed = spd; length = lgth; width = wdth; }

} }

Create an Asteroid object using the Asteroid class

Remember to add the parameters for the

(42)

Practice Creating Objects

namespace hospital {

public class Patient {

private String name; private int ID;

private double weight;

public Patient(String nm, int id, double wght) {

name = nm; ID = id;

weight = wght; }

} }

References

Related documents

An analysis of the economic contribution of the software industry examined the effect of software activity on the Lebanese economy by measuring it in terms of output and value

The summary resource report prepared by North Atlantic is based on a 43-101 Compliant Resource Report prepared by M. Holter, Consulting Professional Engineer,

Prior to the visual search displays, observers were presented with a colour cue that indicated either the target colour (positive cue), the colour of the to-be-ignored

○ If BP elevated, think primary aldosteronism, Cushing’s, renal artery stenosis, ○ If BP normal, think hypomagnesemia, severe hypoK, Bartter’s, NaHCO3,

The 1998 values for CO were around half the expected new limit value (table 7.1). The measured yearly average in 1998 was close to the ex- pected limit value; but the concentrations

Normally Open (N.O.) auxiliary contact is provided for remote indication of High Inlet Dewpoint Alarm. See wiring diagram for actual terminal numbers. Relay is energized during

Different surface and volume mesh quality measures comparison have been given for sequentially generated meshes and meshes constructed by the parallel grid generator.. It has

The Toronto Emergency Management Planning Group (TEMPC) provides the City with an effective vehicle for developing and maintaining a comprehensive Emergency Plan as well as