Objects,
Properties and
Instance Variables
Purpose
•
This presentation describes objects, properties andObjects—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
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
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
Example of Instance
Variables for the Patient
Class
•
Instance variables aredeclared at the class level
•
Are declared with the private public access modifier•
Use camelCase in the identifier•
Can be declared on one line or manyusing System ; class Patient {
private int id;
private string name; private string address; private double weight; private string gender; private double height; // class implementation code
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.Writing Identifiers for Instance
Variables
•
Always use camelCase
•
Use descriptive words
•
Favor length over brevity
Bad Examples: Better Examples: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 methodsProperties in C#
•
Properties have two
assessors
.
•
Assessors allow users to read or write to a data
member
•
The Get assessor returns the property value
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
Why Properties
•
Properties allow programmers to access and change the values of private instance variables.•
Other programmers do not have access to the fieldsthemselves, but have access to the methods that get the values assigned to them or change the values assigned to them
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
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
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 classAn Example of Auto-Implemented
Property
•
Notice when usingauto-implemented properties, the public access modifier is used
•
Notice there is no closing semi-colon outside the curly bracketspublic Name { get { return name; } set {
name = value; }
}
public string name
{get; set;}
The block of code to the right and the one above are
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
Properties Summary
•
Properties are easy to write and access in C#•
When using the public access modifier for instancevariables with properties, C# will automatically create a private instance variable in the background.
Objects and Behaviors
•
Behaviors for objects are defined by methods. For thepatient 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
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
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
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
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
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( )
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 ReadLineMethods
•
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 neededusing 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
Method
Parameters
•
Parameters allowprogrammers 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 ) ; }
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 ) ; }
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.Passing by
Value
•
Consider the following code•
Walk through the code and see if you candetermine 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();
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
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.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
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
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
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
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
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 classPractice 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:
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
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; }
} }