Object Oriented Programming in C#

Similar documents
Chapter 4 Defining Classes I

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

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Principles of Object Oriented Programming. Lecture 4

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Chapter 6 Introduction to Defining Classes

CS313D: ADVANCED PROGRAMMING LANGUAGE

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

CLASSES AND OBJECTS IN JAVA

EEE-425 Programming Languages (2013) 1

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE

Objects and Classes: Working with the State and Behavior of Objects

Final Exam CS 152, Computer Programming Fundamentals December 5, 2014

EEE-425 Programming Languages (2013) 1

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Object Oriented Programming #10

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

int a; int b = 3; for (a = 0; a < 8 b < 20; a++) {a = a + b; b = b + a;}

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

Object-Oriented Programming Concepts

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

BBM 102 Introduction to Programming II Spring 2017

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter 1 Getting Started

Lecture 3. Lecture

G52CPP C++ Programming Lecture 9

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B

Comments are almost like C++

1 Inheritance (8 minutes, 9 points)

Java and OOP. Part 2 Classes and objects

Use the scantron sheet to enter the answer to questions (pages 1-6)

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Recommended Group Brainstorm (NO computers during this time)

More C++ : Vectors, Classes, Inheritance, Templates

Chapter 10 Introduction to Classes

ECOM 2324 COMPUTER PROGRAMMING II

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

CS 231 Data Structures and Algorithms, Fall 2016

Introduction to Classes and Objects. David Greenstein Monta Vista High School

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

Object Oriented Programming

Classes. Classes as Code Libraries. Classes as Data Structures

Methods. Methods. Mysteries Revealed

C++ (Non for C Programmer) (BT307) 40 Hours

Lecture 18 Tao Wang 1

A Foundation for Programming

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

Objectives. Introduce static keyword examine syntax describe common uses

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

COP 3330 Final Exam Review

Programming Language Concepts: Lecture 2

Java Object Oriented Design. CSC207 Fall 2014

Imperative Languages!

Introduction to C# Applications

Fundamental Concepts and Definitions

Ch 7 Designing Java Classes & Class structure

Object-Oriented Programming Concepts

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

Lecture 5: Methods CS2301

Object Oriented Programming COP3330 / CGS5409

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Ch 7 Designing Java Classes & Class structure. Fields have data values define/describe an instance

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

Java Magistère BFA

Questions Answer Key Questions Answer Key Questions Answer Key

CS 1316 Exam 1 Summer 2009

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Introduction to Programming Using Java (98-388)

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

c) And last but not least, there are javadoc comments. See Weiss.

Methods and Data (Savitch, Chapter 5)

PIC 20A The Basics of Java

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

The return Statement

Abstract Data Types (ADT) and C++ Classes

Non-instantiable Classes

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

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

Object Oriented Modeling

EL2310 Scientific Programming

More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

ITI Introduction to Computing II

Transcription:

Introduction to Object Oriented Programming in C# Class and Object 1

You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create instances of a class. 4. Write and use class constructors. 5. Use the static keyword to create class members that are not associated with a particular object. 2

What is a class? Essentially a struct with built-in functions class Circle { double radius = 0.0; } double Area() { return 3.141592 * radius * radius; } 3

Encapsulation By default the class definition encapsulates, or hides, the data inside it. Key concept of object oriented programming. The outside world can see and use the data only by calling the build-in functions. Called methods 4

Class Members Methods and variables declared inside a class are called members of that class. Member variables are called fields. Member functions are called methods. In order to be visible outside the class definition, a member must be declared public. As written in the previous example, neither the variable radius nor the method Area could be seen outside the class definition. 5

Access Modifiers In order to be visible outside the class definition, a member must be declared as one of the following: 1. + : Public 2. - : Private 3. * : Protect 4. ~ : Package 6

Making a Method Visible To make the Area() method visible outside we would write it as: public double Area() { return 3.141592 * radius * radius; } Unlike C++, we have to designate individual members as public. Not a block of members. We will keep the radius field private. 7

A Naming Convention By convention, public methods and fields are named with the first letter capitalized. Also class names. Private methods and fields are named in all lower case. This is just a convention. It is not required, and it means nothing to the compiler. 8

Interface vs. Implementation The public definitions comprise the interface for the class A contract between the creator of the class and the users of the class. Should never change. Implementation is private Users cannot see. Users cannot have dependencies. Can be changed without affecting users. 9

Creating Objects The class definition does not allocate memory for its fields. (Except for static fields, which we will discuss later.) To do so, we have to create an instance of the class. static void Main(string[ ] args) { Circle c; c = new Circle(); } 10

Objects An instance of a class is called an object. You can create any number of instances of a given class. Each has its own identity and lifetime. Each has its own copy of the fields associated with the class. When you call a class method, you call it through a particular object. The method sees the data associated with that object. 11

Using Classes and Objects Classes and objects are used much like traditional types and variables: Declare variables Like pointers to structs Circle c1; Can be member variables in other classes Assignment c2 = c1; Function arguments picture1.crop(c1); 12

Program Circle Demo Demonstrate creating Program Circle in Visual Studio. Demonstrate adding a class to a project Students: Try this for yourself! 13

Create a New Project 14

Create a New Project 15

Program Template 16

Adding a Class to a Program Each class definition should be a separate file. In Visual Studio. Project menu > Add Class Use class name as file name. 17

Add a Class to the Project 18

Adding Class Circle 19

Initial Source File 20

Fill in Class Definition 21

Fill in Main() Call function Area() of Circle object c1 22

Build and Run 23

Program circle_demo in Action Area of Circle c1 24

Constructors So far we have no way to set or change the value of radius of a Circle. We can use a constructor to set an initial value. A constructor is a method with the same name as the class. It is invoked when we call new to create an instance of a class. In C#, unlike C++, you must call new to create an object. Just declaring a variable of a class type does not create an object. 25

A Constructor for Class Circle We can define a constructor for Circle so that it sets the value of radius. class Circle { private double radius;... public Circle (double r) { radius = r; }... } Note: Constructors have no return type. 26

Using a Constructor Calls constructor 27

Program Running Area of Circle c1 28

Multiple Constructors A class can have any number of constructors. All must have different signatures. (The pattern of types used as arguments.) This is called overloading a method. Applies to all methods in C#. Not just constructors. Different names for arguments don t matter, Only the types. 29

Default Constructor If you don t write a constructor for a class, the compiler creates a default constructor. The default constructor is public and has no arguments. c = new Circle(); The default constructor sets numeric variables to zero and Boolean fields to false. In constructors that you write, the same is true for any variables that you don t initialize. 30

Creating multiple objects of the same type 31

Program Running 32

Good Programming Practice All member variables should be private. except const variables Users of the class can use them and manipulate them only by invoking the public methods of the class. Only way for users to do anything with an object. 33

Class Circle Let's extend class Circle by providing names for circle objects. Also provide accessor functions Public functions that let the outside world access attributes of an object. 34

Class Circle New member New constructor Accessor Methods 35

Getting User Input What if we want the user to specify the radius of a Circle at run time? Could overload the constructor and provide a version that asks for input. Better to provide a separate function outside the class definition. Separate User Interface from class logic. Let s write a function that asks the user for a name and a radius and creates a Circle of that radius with that name. 36

Getting User Input In class Program (along with Main() ) static Circle Create_Circle() { } String name, temp; double radius; Console.Write("Please enter name for new Circle: "); name = Console.ReadLine(); Console.Write("Please enter radius: "); temp = Console.ReadLine(); radius = double.parse(temp); return new Circle(name, radius); 37

Main() static void Main(string[] args) { Circle c1 = Create_Circle(); Console.Write("Circle " + c1.name()); Console.WriteLine(" created with radius " + c1.radius()); Console.WriteLine("Its area is " + c1.area()); } Console.ReadLine(); // Keep window open. 38

Running Program Circle End of Section 39

Passing Objects to a Function Let's extend class Circle with a method to compare one Circle to another. In class Circle... Note keyword "this" public bool Is_Greater_Than(Circle other) { } if (this.radius() > other.radius()) { } else { } return true; return false; Call Radius() in Circle object passed as argument. 40

Using "Is_Greater_Than" Method static void Main(string[] args) { Circle Circle_A = Create_Circle(); Console.Write ("Circle " + Circle_A.Name() ); Console.WriteLine (" created with radius " + Circle_A.Radius()); Console.WriteLine ("Its area is " + Circle_A.Area()); Circle c2= Create_Circle(); Console.Write ("Circle " + c2.name() ); Console.WriteLine (" created with radius " + c2.radius()); Console.WriteLine ("Its area is " + c2.area()); 41

Using "Is_Greater_Than" Method if (c1.is_greater_than(c2)) { Console.Write ("Circle " + c1.name() + " is greater than "); Console.WriteLine( "Circle " + c2.name()); } else if (c2.is_greater_than(c1)) { Console.Write ("Circle " + c2.name() + " is greater than "); Console.WriteLine( "Circle " + c1.name()); } else { Console.Write("Circle " + c1.name() + " and Circle " + c2.name()); Console.WriteLine (" are the same size."); } 42

Program Running End of Section 43

Static Fields Sometimes we need a single variable that is shared by all members of a class. Declare the field static. You can also declare a field const in order to ensure that it cannot be changed. Not declared static but is a static variable There is only one instance 44

Static Fields class Math {... public const double PI = 3.14159265358979; } In class Circle -- public double Area() { return Math.PI * radius * radius; } Class name rather than object name. 45

Static Methods Sometimes you want a method to be independent of a particular object. Consider class Math, which provides functions such as Sin, Cos, Sqrt, etc. These functions don t need any data from class Math. They just operate on values passed as arguments. So there is no reason to instantiate an object of class Math. 46

Static Methods Static methods are similar to functions in a procedural language. The class just provides a home for the function. Recall Main() Starting point for every C# program No object 47

Static Methods Example: class Math { public static double Sqrt(double d) {... }... } 48

Static Methods To call a static method, you use the class name rather than an object name. Example: double d = Math.Sqrt(42.24); Note: If the class has any nonstatic fields, a static method cannot refer to them. 49

Static Class A class that is intended to have only static members can be declared static. The compiler will ensure that no nonstatic members are ever added to the class. Class cannot be instantiated. Math is a static class. Book says otherwise on page 138. According to the VS2008 documentation this is incorrect. End of Section 50

Partial Classes In C#, a class definition can be divided over multiple files. Helpful for large classes with many methods. Used by Microsoft in some cases to separate automatically generated code from user written code. If class defintion is divided over multiple files, each part is declared as a partial class. 51

Partial Classes In file circ1.cs partial class Circle { // Part of class defintion... } In file circ2.cs partial class Circle { // Another part of class definition... } 52

Anonymous Classes You can define anonymous classes in the latest version of C#. Class without a name. Described on pages 141 142. Useful in special situations. Ignore for now. 53

Summary A class consists of data declarations plus functions that act on the data. Normally the data is private The public functions (or methods) determine what clients can do with the data. An instance of a class is called an object. Objects have identity and lifetime. Like variables of built-in types. 54

Summary Static members belong to the class as a whole rather than to specific objects. variables methods const variables are automatically static End of Presentation 55