Creating Your Own Classes

Slides:



Advertisements
Similar presentations
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Road Map Introduction to object oriented programming. Classes
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
Advanced Object-Oriented Programming Features
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
C# Programming: From Problem Analysis to Program Design1 2 Your First C# Program.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
1 An Introduction to Visual Basic Objectives Explain the history of programming languages Define the terminology used in object-oriented programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Microsoft Visual Basic 2005: Reloaded Second Edition
Writing Classes (Chapter 4)
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Chapter Eleven Classes and Objects Programming with Microsoft Visual Basic th Edition.
Chapter 11: Introduction to Classes. In this chapter you will learn about: – Classes – Basic class functions – Adding class functions – A case study involving.
10-Nov-15 Java Object Oriented Programming What is it?
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Programming with Microsoft Visual Basic 2012 Chapter 11: Classes and Objects.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Microsoft Visual Basic 2008: Reloaded Third Edition Chapter One An Introduction to Visual Basic 2008.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Microsoft Visual Basic 2012: Reloaded Fifth Edition Chapter One An Introduction to Visual Basic 2012.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Object-Oriented Programming (part 1 – Data Encapsulation)
Introduction to Object-oriented Programming
Topic: Classes and Objects
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Creating Your Own Classes
Programming Logic and Design Seventh Edition
Chapter 7 User-Defined Methods.
3 Introduction to Classes and Objects.
Templates.
Chapter 1: An Introduction to Visual Basic 2015
Advanced Object-Oriented Programming Features
Java Programming: Guided Learning with Early Objects
Microsoft Visual Basic 2005: Reloaded Second Edition
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Classes.
Creating Your OwnClasses
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance Chapter 5.
Introduction to Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Corresponds with Chapter 7
Tutorial 19 - Microwave Oven Application Building Your Own Classes and Objects Outline Test-Driving the Microwave Oven Application Designing.
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
CIS16 Application Development Programming with Visual Basic
Programming with Microsoft Visual Basic 2008 Fourth Edition
Chapter 9 Objects and Classes
Today’s topics UML Diagramming review of terms
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Object-Oriented Programming: Inheritance and Polymorphism
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Final and Abstract Classes
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Chapter 7 Objects and Classes
Presentation transcript:

Creating Your Own Classes 4 C# Programming: From Problem Analysis to Program Design 4th Edition C# Programming: From Problem Analysis to Program Design

Chapter Objectives Become familiar with the components of a class Learn about the different methods and properties used for object-oriented development Create and use constructors Write your own instance methods to include mutators and accessors Call instance methods including mutators and accessors Work through a programming example that illustrates the chapter’s concepts C# Programming: From Problem Analysis to Program Design

The Object Concept Solutions are defined in terms of a collection of cooperating objects Class serves as template from which many objects can be created Abstraction Identify real-world entities and represent them as classes. For each class indicate Attributes (data) Behaviors (processes on the data)

Example1 – A Classical View of a Class Diagram Graphical key Style1. The 'classical' class representation is not tied to any specific programming language. Instead, it is based on the Unified Modeling Language (UML) It emphasizes visibility of data and behavior. PERSON Attributes - personName : string - personAge : int Constructor(s) + Person() + Person(string nameValue, int ageValue) Accessors / Mutators + GetPersonName() : string + SetPersonName(string nameValue) + GetPersonAge() : int + SetPersonAge(int ageValue) User-Defined Methods + ToString() : string … other methods here … Data Behavior Person class → This style is commonly used by Java and C++ developers.

Example2 – C# Class Diagrams: Geometric Figures Style 2. The C#-styled depiction of a class emphasizes the class - Fields (usually private), - Properties (field accessors), - and Methods.

Example3 – University Seminar - Class Diagram Note: This UML Class Diagram shows multiple cooperative classes as well as the associations (links) between them.

Example4 – An Inventory System - Class Diagram

Example5 – A Library System

Example6 – Class Inheritance This diagram shows the super-class Person and two descendant classes Student and Faculty, that generalize the ancestor class. We will study Inheritance in chapter 11.

Writing Your Own Classes Implicit "contractual obligations" of a C# software developer to be followed when creating a class. Provide: Properties (in VS use propf hot-key combination, it combines a private data member, and its associated get/set accessors). Constructors (at least the Zero-Args and All-Args version). User-defined methods to perform behaviors of the class. Always include a version of the ToString() method.

Making a Class - Private Member Data Observations Begin by identifying the class data members. When you define a class, you declare instance variables or fields that represent states of an object. Fields become visible to the component of the defining class, including all of its methods. Private fields cannot be seen outside of the class in which they are defined. Public fields are visible inside and outside the class, this is a DANGEROUS PRACTICE! Data members are almost always defined to have private access. All code you write is placed in a class (and saved in a separate file). Graphical key

C# Implementation of Private Member Data (continued) public class Student { //Data members (data fields, or characteristics) private string studentNumber; private string studentLastName; private string studentFirstName; private int score1; private int score2; private int score3; private string major; . . . } All data member names should be entered using Camel-Notation. Their corresponding property names should use Pascal-Notation (later)

How to Create a Class using VS? There are two options for adding a new class to a C# project. After you create the new class, you could either - Type-in its code, or - 'Draw' it using the Class Diagram Tool. DRAWING THE CLASS Use the top PROJECT menu or the Solution Explorer Window On 'Solution Explorer', point to the app's namespace entry. Right-click the entry. On the pop-up window select the option Add > New item > Class.cs Enter a name for the new item. Text editor opens showing the skeleton of the new class. On the Solution Explorer panel, point to the new class. Right-Click it. On the pop-up window choose 'View Class Diagram'

Figure 4-1 Student class diagram created in Visual Studio Open the Class Diagram from Solution Explorer (right-click) View Class Diagram Private member variables → In VS2017 you need to install the graphic design tool. Go to menu Tools-> Get Tools and Features. Pick 'Visual Studio extension development' workload, choose 'Class Designer' option. Install. Public Properties (accessors) → User –Defined Methods → Figure 4-1 Student class diagram created in Visual Studio

Class Diagram (continued) After the class diagram is created, add the names of data members or fields and methods using the Class Details section Right click on class diagram to open Class Details window Figure 4-2 Student class diagram details

Class Diagram (continued) When you complete 'drawing' the Student class using the Class Diagram tool, its corresponding code is automatically placed in the file Student.cs Figure 4-3 Skeleton of auto generated code made for the Student class diagram

Creating Objects from Classes Classes are blueprints from which objects are made or instantiated. Assume the Student class has been defined already. We may create two object s1 and s2 representing two different students as follows. Student s1 = new Student("1000", "Daenerys", "Targaryen", 99, 100, 100, "Political Sc."); Student s2 = new Student("1000", "Lannister", "Cersei", 50, 55, 65, "Social Services"); The keyword new is used to call the constructor that best fits the type and number of parameters passed in the invocation. If the object is created the system returns a reference to the it, otherwise it send back the value null.

Parts of a class: Constructors Special type of method used to create objects Create instances of class Instantiate the class Constructors differ from other methods Constructors do not return a value, neither they include the void keyword void. Constructors use same identifier (name) as class Constructors use public access modifiers

Constructor (you need to type in this code) Constructors are always given public access. //Default constructor - ZERO ARGUMENTS CONST. public Student() { studentNumber = "9999999"; studentLastName = "n.a."; studentFirstName = "n.a."; score1 = 0; score2 = 0; score3 = 0; major = "Not declared yet"; } //Constructor with six arguments - ALL AGRGUMENTS CONST. public Student(string numberValue, string lastNameValue, string firstNameValue, int s1Value, int s2Value, int s3Value, string majorValue) studentNumber = numberValue; studentLastName = lastNameValue; studentFirstName = firstNameValue; score1 = s1Value; score2 = s2Value; score3 = s3Value; major = majorValue; (must) (must)

Constructor (continued) //Constructor with three parameters (optional) public Student (string idValue, string firstValue, string lastValue) { studentNumber = idValue; studentFirstName = firstValue; studentLastName = lastValue; } Conventions regarding constructors Constructors should be the ONLY class methods that directly access the private data members. All other methods should use the class Properties (explained later). A good programming practice is to always include the Zero-arguments and the All-arguments constructors.

Moving Data In/Out of Class There are two C# strategies used to safely introduce and retrieve data into/from a private data member Use Get – Set accessors (Typical of Java, C++) Use Properties (unique to C#) Student Data Methods Get methods 'extract' data from the class Set methods 'carry' data into the class Value Traditional approach to data traffic control in a class

Accessors – Classic Style (Java, C++, etc.) Getter Method Returns the current value of a private data member. Standard naming convention, for each private data member create a method prefixed with “Get”, use Pascal-Notation (e.g. GetMajor() ) Example. Accessor for the private member studentNumber public double GetStudentNumber( ) { return studentNumber; } Get Accessor Student Data Methods Get methods 'extract' data from the class

Accessors – Classic Style (Java, C++, etc.) Setter Methods (Mutators) Normally include only one parameter. Here you may implement 'business rules' at the item level. For instance, scores must be positive, age less than a120, etc. Standard naming convention → prefix with ”Set”, use Pascal notation Example. Consider the Student class. Assign a grade to score1. public void SetScore1( int gradeValue) { if (gradeValue < 0) //convert negative grades to zero gradeValue = 0; } score1 = gradeValue; Student Data Methods Set methods 'carry' data into the class value

Accessors – Classic Style (Java, C++, etc.) public double SetNoOfSqYards(double squareYards) { noOfSquareYards = squareYards; } public void SetNoOfSquareYards(double length, double width) noOfSquareYards = length * width; Mutator Overloaded Accessors could be overridden

User-defined Methods User-defined methods Declared in the same class as the data members Instance methods can directly access private data members Not meant to be used for data exchange; instead typically used for calculating a value using private data members public double CalculateAverage( ) { return (score1 + score2 + score3) / 3.0; }

Using C# Property This is the recommended Approach Can replace accessors and mutators. They 'fuse' together a private data member with their get- set accessors. Properties looks like a public data field (but they are not!) Standard naming convention in C# for properties Use the same name as the instance variable or field, but start with uppercase character. For example, if private data member is studentMajor its property should be StudentMajor.

C# Property class Student { //private data members ... private int score1; //Properties public int Score1 get { return score1; } set //convert incoming negative grades to zero if (value < 0) value = 0; } score1 = value; //...rest of the class goes here ... value is a special C# variable used as general alias for input data arriving to a property.

Property (continued) What is the meaning of value used by properties? Assume we have created an object s1 representing an instance of the Student class. Assigning a grade to her first test could be done as follows s1.Score1 = 100; Here, 100 is the value supplied to the property Score1.

ToString( ) Method All classes inherit four methods from the super Object class ToString() //show yourself! Equals() //are you equal to this other object? GetType() //tell what type of data item you are GetHashCode() //tell your unique identifier code Use ToString() to produce a 'nice looking' display of the object, telling all of its data. ToString() method is called automatically by several methods Write() WriteLine() The following statements are equivalent Console.WriteLine(s1); Console.WriteLine(s1.ToString());

ToString( ) Method (continued) Returns a human-readable string Can write a new definition for the ToString() method to include useful details public override string ToString( ) { // return string value } Keyword override added to provide new implementation details It is understood that we must always override the ToString() method. This enables us to decide what should be displayed if the object is printed

Example - ToString( ) Consider the Student class. public override string ToString() { string niceOutput = "Student [" + " No: " + StudentNumber + " First: " + StudentFirstName + " Last: " + StudentLastName + " Score1: " + Score1 + " Score2: " + Score2 + " Score3: " + Score3 + " Major: " + Major + "]"; return niceOutput; } If the method is NOT overridden the object would be displayed as it appears on the right

Calling Instance Methods Instance methods are generally nonstatic. They must be called with objects – not classes. The syntax for the invocation is object.method(args) Assume object s1 is an instance of the Student class. You may call the non-static CalculateAverage() method as follows: finalGrade = s1.CalculateAverage(); As a counter example, static calls to members of Math and Console classes uses syntax ClassName.method(args) answer = Math.Pow(4, 2); Console.WriteLine("hello"); If you need to invoke a method inside the class in which it is defined, simply use the method's name (no qualifier needed).

Testing Your New Class A different class is needed for testing and using your class Test class has Main( ) in it Construct objects of your class Use the properties to assign and retrieve values Invoke instance methods using the objects you construct C# Programming: From Problem Analysis to Program Design

Calling the Constructor Method Figure 4-4 Intellisense displays available constructors C# Programming: From Problem Analysis to Program Design

Using Public Members Discovering public Properties (wrench icon) and Methods (purple box icon) exposed by the VisualStudio IDE. Type object's name followed by a dot. Intellisense responds with a panel listing available components. Figure 4-5 Public members of the Student class

StudentApp Figure 4-6 Output from StudentApp Review StudentApp Project C# Programming: From Problem Analysis to Program Design

Test Class With multiclass solutions all input and output should be included in the class that has the Main( ) method Eventual goal will be to place your class files, like Student and CarpetCalculator, in a library so that the classes can be used by different applications Some of these applications might be Windows applications; some may be console applications; others may be Web application Do not include ReadLine( ) or WriteLine( ) in your class methods

Testing Your New Class Review CarpetCalculator Project Figure 4-7 Output from Carpet example using instance methods Review CarpetCalculator Project

Example - English Distance Class Problem Implement a class representing distances (feet and inches) using the Imperial English Distance model. Inches value must be normalized (cannot be greater than 12) Provide a method to convert distance to meters.

Example - English Distance Class 1 of 4 class EDistance { //OK to make constant publicly available (prefix EDistance.) public const double INCHES_TO_CM = 2.54; //properties & private members private int feet; private int inches; public int Inches get { return inches; } set //correct inches in case they are > 12 feet += value / 12; inches = value % 12; }

Example - English Distance Class 2 of 4 public int Feet { get { return feet; } set { feet = value; } } //constructor(s) public EDistance() //Observe, we use properties, not the priv. vars. Feet = 0; Inches = 0; public EDistance(int feetValue, int inchesValue) //Style: add postFix Value to each incoming argument Feet = feetValue; Inches = inchesValue;

Example - English Distance Class 3 of 4 //user-defined methods public override string ToString() { return string.Format("Edistance [ {0}\' {1}\" ]", Feet, Inches); } public double ToMeters() double cm = (12 * Feet + Inches) * INCHES_TO_CM; return cm / 100;

Example - English Distance Class 4 of 4 //Testing the EDistance class class Program { static void Main(string[] args) //call the all-arguments constructor EDistance ed1 = new EDistance(6, 2); Console.WriteLine(ed1); Console.WriteLine(ed1.ToMeters()); //call the zero-arguments constructor EDistance ed2 = new EDistance(); ed2.Feet = 3; ed2.Inches = 14; Console.WriteLine(ed2); Console.Read(); }

RealEstateInvestment Example Figure 4-8 Problem specification for RealEstateInvestment example

Data for the RealEstateInvestment Example Table 4-2 Instance variables for the RealEstateInvestment class

Data for the RealEstateInvestment Example (continued) Table 4-3 local variables for the property application class C# Programming: From Problem Analysis to Program Design

RealEstateInvestment Example (continued) Figure 4-9 Prototype C# Programming: From Problem Analysis to Program Design

RealEstateInvestment Example (continued) Figure 4-10 Class diagrams C# Programming: From Problem Analysis to Program Design

RealEstateInvestment Example (continued) Table 4-4 Properties for the RealEstateInvestment class C# Programming: From Problem Analysis to Program Design

RealEstateInvestment Example (continued) Figure 4-11 Structured English for the RealEstateInvestment example C# Programming: From Problem Analysis to Program Design

Class Diagram Figure 4-12 RealEstateInvestment class diagram C# Programming: From Problem Analysis to Program Design

View RealEstateInvestment Test and Debug Figure 4-13 Output from RealEstate Investment example View RealEstateInvestment C# Programming: From Problem Analysis to Program Design

Coding Standards Naming Conventions Constructor Guidelines Classes Properties Methods Constructor Guidelines Spacing Guidelines C# Programming: From Problem Analysis to Program Design

Resources C# Coding Standards and Best Practices – http://www.dotnetspider.com/tutorials/BestPractices.aspx C# Station Tutorial - Introduction to Classes – http://www.csharp-station.com/Tutorials/Lesson07.aspx Object-Oriented Programming – http://msdn.microsoft.com/en-us/library/dd460654.aspx Introduction to Objects and Classes in C# http://www.devarticles.com/c/a/C-Sharp/Introduction-to-Objects-and-Classes-in-C-sharp/ C# Programming: From Problem Analysis to Program Design

Chapter Summary Components of a method: modifiers + returnType + methodName + parameters + body Class methods Parameters: value, ref, out, default values Predefined methods (ToString, Equals,…) Value- and nonvalue-returning methods C# Programming: From Problem Analysis to Program Design

Chapter Summary (continued) Properties Instance methods Constructors Mutators / Accessors User-defined methods Types of parameters C# Programming: From Problem Analysis to Program Design