Working with Objects. Overview. This chapter covers. ! Overview! Properties and Fields! Initialization! Constructors! Assignment

Similar documents
Chapter 1 Getting Started

MITOCW watch?v=kz7jjltq9r4

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

printf( Please enter another number: ); scanf( %d, &num2);

Chapter 7 Classes & Objects, Part B

IT 374 C# and Applications/ IT695 C# Data Structures

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

For this chapter, switch languages in DrRacket to Advanced Student Language.

Your First Windows Form

Chapter 10 Recursion

Chapter 11 Generics. Generics. Hello!

************ THIS PROGRAM IS NOT ELIGIBLE FOR LATE SUBMISSION. ALL SUBMISSIONS MUST BE RECEIVED BY THE DUE DATE/TIME INDICATED ABOVE HERE

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

6.001 Notes: Section 17.5

MITOCW MIT6_01SC_rec2_300k.mp4

Software Design and Analysis for Engineers

Programming Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science Indian Institute of Technology, Madras

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Thursday, February 16, More C++ and root

Notes on Chapter Three

Introduction To C#.NET

An Introduction to C++

MITOCW watch?v=flgjisf3l78

Object oriented programming Concepts

MITOCW watch?v=4dj1oguwtem

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Slide 1 CS 170 Java Programming 1

MITOCW watch?v=hverxup4cfg

6.001 Notes: Section 15.1

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

Programming Languages (Outsource: 2-2)

1 Getting used to Python

COPYRIGHTED MATERIAL. Starting Strong with Visual C# 2005 Express Edition

Programming Using C# QUEEN S UNIVERSITY BELFAST. Practical Week 7

Basic Object-Oriented Concepts. 5-Oct-17

COMP 250 Fall inheritance Nov. 17, 2017

BEGINNER PHP Table of Contents

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Chapter 6 Classes and Objects

Pointers, Arrays and Parameters

Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

Lecture 34 SDLC Phases and UML Diagrams

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

In our classes, we've had

G52CPP C++ Programming Lecture 9

If Statements, For Loops, Functions

Introduction to Programming Using Java (98-388)

Introductory ios Development

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Chapter 15: Object Oriented Programming

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Hands-On Lab. Introduction to F# Lab version: Last updated: 12/10/2010. Page 1

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

1. Write two major differences between Object-oriented programming and procedural programming?

Fundamental C# Programming

Creating a Class Library You should have your favorite version of Visual Studio open. Richard Kidwell. CSE 4253 Programming in C# Worksheet #2

Math Modeling in Java: An S-I Compartment Model

Intro. Classes Beginning Objected Oriented Programming. CIS 15 : Spring 2007

Objective-C. Stanford CS193p Fall 2013

(Refer Slide Time: 4:00)

CS Problem Solving and Object-Oriented Programming

Fortunately, you only need to know 10% of what's in the main page to get 90% of the benefit. This page will show you that 10%.

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Software Design and Analysis for Engineers

The Parts of a C++ Program

A A B U n i v e r s i t y

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211

Week - 01 Lecture - 04 Downloading and installing Python

IT150/IT152 Concepts Summary Sheet

Lesson 3: Accepting User Input and Using Different Methods for Output

The Essence of Object Oriented Programming with Java and UML. Chapter 2. The Essence of Objects. What Is an Object-Oriented System?

vi Primer Adapted from:

Collections, Maps and Generics

Chapter 5 Object-Oriented Programming

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

Chapter 1: Object-Oriented Programming Using C++

Introduction to Game Programming Lesson 4 Lecture Notes

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

GEA 2017, Week 4. February 21, 2017

CS 61B Discussion 4: Inheritance Fall 2018

Rules and syntax for inheritance. The boring stuff

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently.

This chapter is intended to take you through the basic steps of using the Visual Basic

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

(Refer Slide Time: 00:23)

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Super-Classes and sub-classes

And Even More and More C++ Fundamentals of Computer Science

Inheritance & Polymorphism

Transcription:

4 Working with Objects 41 This chapter covers! Overview! Properties and Fields! Initialization! Constructors! Assignment Overview When you look around yourself, in your office; your city; or even the world, there are objects. Each of these object have specific properties and behaviors and some of these object would have common properties and behaviors. For example, cats have behaviors such as meowing, scratching, and sleeping where as dogs bark, chewing, and fetching a ball. Properties include ears, teeth, and tails. But, when you think about it, they both share properties and behaviors; they are both animals and make sounds. The foundation to learning object-oriented programming is understanding classes and objects. We have already learned that C# has types for numbers and strings. Classes allow you to define new types - complex types where these types have fields, properties, methods and constructors and we will talk in depth about all of these.

42 Properties and Fields Let's create a new program and take a look at the creation of classes and objects; as usual, we ll create a new Windows C# Console Application and name it ClassProgram. The first thing to understand is that classes should be created in their own file a class file. To do this, you need to right-click over top of the project name ClassProgram as shown below: You should be shown a large list of options that can be performed on a project but we are wanted to add a new item to the project a new class. Hover over top of the Add option and when presented with yet another list of items, select Class. You ll be presented with the Add Item dialog screen with the Class item selected in the list of items. At the bottom of the dialog, enter the name Employee.cs and click on the Add button. Once done, your new file should appear in the list of files in your project as shown on the right. Now this class might be used in any number of programs to represent employees in a company. There are many fields and properties that a typical employee might have, but let's talk about fields and properties for a moment and get that distinction clear, and then talk about how we use properties in modern C#. A Class Field A field is just a member and it can be private or public. Private means that the field can only be seen by methods of the class itself; in our case the Employee Class. When we declare a field as Public, it can be seen by any method of any class. Later we'll take a look at what the C# Fundamentals

43 difference is but for now let's start simple public field of type integer - the employee's age and for the purpose of learning we will just add this one field. Now, click on the Program.cs file and lets make an instance of Employee - or an Employee object. Instance and object are really the same thing they are synonymous. Let s review the following example: In the example above, notice how we create a new instance of Employee. This is quite similar to creating a new string variable; we start with typing the Name of the Class (Employee) followed by the name of the variable in our case allan. The main difference is that we new to make it equal (or assign it) to a new Employee(). This is basically saying Create a spot in memory that will hold an Employee object. Once we have an instance of the Employee Object, we can access the fields that are defined in this new object. The next line is doing just that; we are assigning the age field and assigning it the integer number 27. Lastly, to test that our new object now has this new age value, we ll output it to the console, as shown on the right. That all works just fine, but age is part of the internal state of the employee, and one of the key concepts in object-oriented programming, encapsulation and data hiding, indicate that we should not have this data be public. It should not be available to the function main, which is not a function of the employee class. A Property Best practices in object-orientated programming state that this field should be private to the class employee, and access to that should be mediated through a property. The reason for that, among others, is that you may change the way you hold or store the employee age. You may decide at a later time to get that from a database or to compute that from the employee's birthdate and the current date. So, the more common way, and preferred way, to handle this is to make age private. Then, what we'd like is something that looks like a field to this client, but acts like a method to this employee object, and that's where properties come in. Let s examine the following: With a property, what we can do is come along and say public int Age, and it's common in C# to have the private backing variable be lowercase and the public variable be initial uppercase.

44 Remember C# is case sensitive, so those are different. Public int Age. And then within the braces, we create a getter and a setter. And the getter will just return the private variable age, and the setter will just set the private variable age to value. And what's value? Value is a hidden parameter that is passed into set. Now, let s add another property to our Employee Class Name, as shown on the right: Just like our Age property, we have now added a Name property; a backing variable named name with a property defined as Name with, again, a getter and a setter. They way these properties are used back in our main program is like this. The way the program using an instance of this Employee class is when it wants to set the age we say allan.age = 35. Notice that to the main program this looks like you're working with a field. You simply set the Age equal to 35. That calls the setter automatically and the 35 is passed in as the value automatically, and the backing variable age is then set. We can then get the age by saying allan.age and the getter is called automatically and the backing field is retrieved and returned.. So, a lot of that work is done for you. And now you have a private member age, which you can change later to be computed or whatever you want, and a public getter and setter that the user can use as if they were accessing a field directly, and this works just as well as the previous example. Similarly, the same happens for the Name property; setting the Name = Allan (for example) passes the string Allan as the value in the setter and when you access the Name property for retrieving the name the getter is called, as shown below: A Better way to create Properties But it gets even better. This is such a common repetitive coding task; to have a backing variable called age and another public variable called Age (with a capital) and a getter that just returns it and a setter that just sets it. Rather than having to type that again and again as we're doing here with the name field and property; rather than doing that and having many of these all using the same format; there's an incredibly convenient shortcut as shown below: C# Fundamentals

45 The new Employee class with its two properties Name and Age is the equivalent to all of the code we had before. In essence, the compiler sees these two lines of code and creates what we had before; a backing variable, the public property, and the properties getters and setters remember, we hate typing and these types of short cuts helps us focus more on the application than typing repetitive code over and over. I should note that at any time, you can expand one of these properties and put more into the getter or more into the setter, but if you need just the standard get and set and want to use properties instead of fields, this new short syntax is tremendously useful. And notice that I didn t need to make any changes to the body of my program inside main. We still use allan.age to set and get the value, and, in fact, when we run it we get the same results. Initialization and Constructors At this point we have an Employee Class that has two properties. Let's give it a few more: As shown above, I've added a salary, a starting date, and a phone number. When we instantiated our employee allan, we did this using the new Employee(). There are three ways to get data into that instance of allan and we have already used one of them by simply assigning the properties to the new object one at a time (allan.age = 27 and allan.name= Allan ). A second way of assigning data to the object is through a process called initialization. With initialization, at the time we create the employee, we can also initialize one or more of the properties. Let s examine the following piece of code:

46 This may look a little confusing at first glance and there are a few different new things to explain but once to work with this type of initialization a few times it will become second nature. Initialization First, after the new Employee() we are replacing the semi-colon with an open and closing squiggly brace a block. Inside of this we have access to all of the public properties and can assign them at the time of creating the new instance of Employee. In many ways, this is quite similar to how we were assigning the properties before but now we can save a bunch of typing by not having to have the allan. object reference in front of the property names. Also in the example above I am introducing a couple new shortcuts; the first is assigning a date to the DateTime object defined in the employee class. DateTime is a date and time class in the.net Framework and offers a complete list of functionality when dealing with dates and Time. Similar to how we create a new Employee class we are creating a new DateTime object and accessing one of its constructors (more on this later) that requires a year, month and then a day; this returns a new constructed object with the date October 28, 2010. The other new bit of code I am using is how I m using the Console.WriteLine. Instead of having five separate calls to WriteLine for each of the properties in our employee object, I am inserting a \n between the properties which just instructs the Console.WriteLine to place a new line after each property. The output is as shown on the right. The other, and third, way of initializing the fields in the new object is through a special method called a Constructor. Now, we've only alluded to methods, but methods are simply functions that are members of the class. And most methods are very normal in that they have a return type or void, they take 0 or more parameters, and there's a body containing statements - to the method. So, for example, we might give the employee class a method called AssignBonus. So, let's look at this method that we've added to our employee class called AssignBonus. Reviewing our new Employee Class we can see that AssignBonus does not return a value, so we have it return void, it takes one argument of type double called increasepercentage, and what it does is it does is it adds to the salary, Salary * increasepercentage. C# Fundamentals

47 In our running program that we've been building, let s give allan a bonus by calling allan.assignbonus and passing in 5 percent as shown below: allan.assignbonus(0.05); And, when we run the application we see that allan is now making $78,750 from his previous salary of $75,000 a 5% increase. So, that's a standard method of a class, but we we're talking about constructors. I just wanted to create a standard method so that you d see how Constructors are different. Constructors Constructors are special methods of the class, and they are used to construct an instance. What's interesting about constructors is that they don't have a return type at all, not even void, and they must have the name of the class itself, in our case, Employee. However, they do typically take parameters, and what is very common is for them to have a parameter for each of the properties of the class. So, our constructor might have an int for age and a string for name and so on for each of the various properties. Then within the body of the body of the constructor, you can assign these passed in parameters to the property. And so you can say Age = age and Name = name and so forth; as shown here in the Constructor shown below: Now, you have a way of constructing the object by passing parameters into the constructor at the time you create the object. Notice in our current code we are creating an instance of Employee and with nothing in the brackets and now, in fact, has the squiggly line below it indicating that we have an error. Any constructor that has no parameters is called a default constructor, and, in fact, if you don't create a constructor, you are given a default constructor by default. That default constructor, which takes no parameters, does nothing. This is why we had to do the initialization. However, now that I've created a constructor, I no longer get my free default constructor in the

48 Employee Class need to supply my own Constructor that contains no parameters. Fortunately, we can do something called method overloading where we have two methods with the same name, but different parameters, either different types or a different number of parameters. Let s add a another Constructor using method overloading. Now, we can instantiate an Employee without parameters as we have thus far or we can instantiate an employee by passing in values, where these values would then be passed into the constructor with parameters. Let s give this a try; we ll create a new employee, Mary = new Employee but this time we're going to use our second constructor. You should notice that IntelliSense will now show us that we have two constructors now and if I het the down arrow it will display the new constructor with all of the parameters we defined. Also, as you enter the values to be passed to our new constructor IntelliSense makes it very easy to fill them in because it takes you through them on-by-one. So, the first one is Mary's Name, we'll make her 39, and let's give her a salary of 50000 dollars. Her start date, which will be a new DateTime of February 17, 2008. Hit the comma, and it says you still need the phone number as a string, let s enter 780.555.3131 shown below: Now, we have created an employee, not by initializing it, by passing in values to the constructor, and yet, we can once again add a Console.WriteLine. And now let's run the program, and we've got Mary's age is 39, she started on February 17 th, and makes 50000. Key here is we were able to set all of the values in the employee object through the constructor that took those arguments. We could, of course, have a constructor that takes some arguments and not others, and we can even use initialization when we have a constructor. So, you can mix and match these various ways of putting data into your object. C# Fundamentals

49 Summary In this chapter, we talked about classes and objects, and we saw how classes define a type and objects are instances of that type. Classes can have fields, which are the data for the class, and they can have properties, which are the way that other methods of other classes interact with the data of the class. Classes can also have methods, which represent the behavior of the objects in that class. An instance of a class is called an object, and classes exist to instantiate objects, each of which has its own data. The constructor can be used to create an instance of a class and to populate the data of that class. A constructor that takes no arguments is called a default constructor, and if you don't create any constructors for your class, you will receive a default constructor by default. We also looked at initialization in which you can set the values of the members of the class at the time you create it.

50 C# Fundamentals