Creating Your Own Classes

Slides:



Advertisements
Similar presentations
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Section 5 – Classes. Object-Oriented Language Features Abstraction –Abstract or identify the objects involved in the problem Encapsulation –Packaging.
Road Map Introduction to object oriented programming. Classes
C# Programming: From Problem Analysis to Program Design1 Methods and Behaviors C# Programming: From Problem Analysis to Program Design 3rd Edition 3.
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.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
C# Programming: From Problem Analysis to Program Design1 10 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
ASP.NET Programming with C# and SQL Server First Edition
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
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.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
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.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
C# Programming: From Problem Analysis to Program Design1 10 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Chapter 4 Introduction to Classes, Objects, Methods and strings
C# Programming: From Problem Analysis to Program Design1 4 Methods and Behaviors.
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 3 Introduction to Classes and Objects Definitions Examples.
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.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
C# Programming: From Problem Analysis to Program Design
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
1 Introduction to Object Oriented Programming Chapter 10.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Microsoft Visual C#.NET: From Problem Analysis to Program Design1 Chapter 4 Methods and Behaviors Microsoft Visual C#.NET: From Problem Analysis to Program.
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.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Object-Oriented Programming (part 1 – Data Encapsulation)
Topic: Classes and Objects
Classes (Part 1) Lecture 3
Programming Logic and Design Seventh Edition
Chapter 7 User-Defined Methods.
Chapter 1: An Introduction to Visual Basic 2015
Advanced Object-Oriented Programming Features
Reference: COS240 Syllabus
Microsoft Visual Basic 2005: Reloaded Second Edition
Chapter 3: Using Methods, Classes, and Objects
Creating Your OwnClasses
Creating Your Own Classes
CSC240 Computer Science III
User-Defined Classes and ADTs
Can perform actions and provide communication
Chapter 3 Introduction to Classes, Objects Methods and Strings
Can perform actions and provide communication
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
Lecture 22 Inheritance Richard Gesick.
Programming with Microsoft Visual Basic 2008 Fourth Edition
CSCI 3328 Object Oriented Programming in C# Chapter 9: Classes and Objects: A Deeper Look – Exercises UTPA – Fall 2012 This set of slides is revised from.
Chapter 9 Objects and Classes
Chapter 8: User-Defined Classes and ADTs
Can perform actions and provide communication
Chapter 8 Classes User-Defined Classes and ADTs
Data Types and Expressions
CIS 199 Final Review.
Lecture 8 Object Oriented Programming (OOP)
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 Attributes (data) Behaviors (processes on the data) C# Programming: From Problem Analysis to Program Design

Private Member Data All code you write is placed in a class When you define a class, you declare instance variables or fields that represent state of an object Fields are declared inside the class, but not inside any specific method Fields become visible to all members of the class, including all of the methods Data members are defined to have private access C# Programming: From Problem Analysis to Program Design

Private Member Data (continued) public class Student { private int studentNumber; private string studentFirstName; private string studentLastName; private int score1; private int score2; private int score3; private string major;

Add a Class Use the PROJECT menu or the Solution Explorer Window Right-mouse click and select the option Add, Class Solution Explorer Window enables you to create a class diagram C# Programming: From Problem Analysis to Program Design

Figure 4-1 Student class diagram created in Visual Studio Open the Class Diagram from Solution Explorer (right-click) View Class Diagram 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 class details using the Class Diagram tool, code is automatically placed in the file. Figure 4-3 Auto generated code from Student class diagram

Constructor 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 (continued) public access modifier is always associated with constructors //Default constructor public Student ( ) { } //Constructor with one parameter public Student (int sID ) studentNumber = sID;

Constructor (continued) //Constructor with three parameters public Student (string sID, string firstName, string lastName) { studentNumber = sID; studentFirstName = firstName; studentLastName = lastName; } Design classes to be as flexible and as full-featured as possible Include multiple constructors

Writing Your Own Instance Methods Constructors Accessors Mutators Other methods to perform behaviors of the class C# Programming: From Problem Analysis to Program Design

Writing Your Own Instance Methods Do not use static keyword Static associated with class method Constructor – special type of instance method Do not return a value void is not included Same identifier as the class name Overloaded Default constructor No arguments Write one constructor and you lose the default one

Accessor Accessor Getters Returns the current value Standard naming convention → prefix with “get” Accessor for noOfSquareYards public double GetNoOfSqYards( ) { return noOfSqYards; } Accessor

Mutators Setters Normally includes one parameter Method body → single assignment statement Standard naming convention → prefix with ”Set” Can be overloaded C# Programming: From Problem Analysis to Program Design

Mutator Examples Overloaded Mutator public double SetNoOfSqYards(double squareYards) { noOfSquareYards = squareYards; } public void SetNoOfSquareYards(double length, double width) noOfSquareYards = length * width; Overloaded Mutator

Other Instance Methods User-defined methods Defined 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; }

Property Can replace accessors and mutators Properties looks like a data field More closely aligned to methods Standard naming convention in C# for properties Use the same name as the instance variable or field, but start with uppercase character Doesn’t have to be the same name – no syntax error will be thrown C# Programming: From Problem Analysis to Program Design

Property public double NoOfSqYards { get return noOfSqYards; } set noOfSqYards = value;

Property (continued) If an instantiated object is named berber, to change the NoOfSqYards, write: berber.NoOfSqYards = 45; C# Programming: From Problem Analysis to Program Design

ToString( ) Method All user-defined classes inherit four methods from the object class ToString( ) Equals( ) GetType( ) GetHashCode( ) ToString( ) method is called automatically by several methods Write( ) WriteLine( ) methods Can also invoke or call the ToString( ) method directly

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 Always override the ToString( ) method This enables you to decide what should be displayed if the object is printed

ToString( ) Example public override string ToString( ) { return "Price Per Square Yard: " + pricePerSqYard.ToString("C") + "\nTotal Square Yards needed: " + noOfSqYards.ToString("F1") + "\nTotal Price: " + DetermineTotalCost( ).ToString("C"); }

ToString( ) method pricePerSqYard.ToString("C") Sometimes useful to add format specifiers as one of the arguments to the Write( ) and WriteLine( ) methods – Invoke ToString( ) Numeric data types such as int, double, float, and decimal data types have overloaded ToString( ) methods pricePerSqYard.ToString("C") C# Programming: From Problem Analysis to Program Design

Calling Instance Methods Instance methods are nonstatic method Call nonstatic methods with objects – not classes Static calls to members of Math and Console classes answer = Math.Pow(4, 2); Console.WriteLine( ); If you need to invoke the method inside the class it is defined in, simply use method name If you need to invoke the method outside the class it is defined in, precede method name with object identifier berber.GetNoOfSquareYards( )

Calling the Constructor Normally first method called Creates an object instance of the class ClassName objectName = new ClassName(argumentList); or ClassName objectName; objectName = new ClassName(argumentList); Keyword new used as operator to call constructor methods CarpetCalculator plush = new CarpetCalculator ( ); CarpetCalculator pile = new CarpetCalculator (37.90, 17.95);

Constructor (continued) Default values are assigned to variables of the value types when no arguments are sent to constructor Table 4-1 Value type defaults

Calling Accessor and Mutator Methods Method name is preceded by the object name berber.SetNoOfSquareYards(27.83); Console.WriteLine("{0:N2}", berber.GetNoOfSquareYards( )); If property defined, can use property instead of accessor and/or mutators Using properties PropertyName = value; // Acts like mutator here Console.Write("Total Cost at {0:C} ", berber.Price); // Acts like accessor here

Calling Other Instance Methods Call must match method signature If method returns a value, must be a place for a value to be returned Student aStudentObject = new Student("1234", "Maria", "Smith", 97, 75, 87, "CS"); average = aStudentObject.CalculateAverage( ); No arguments needed as parameters to the CalculateAverage( ) method. CalculateAverage( ) is a member of the Student class and has full access to all Student members.

Testing Your New Class 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 Figure 4-5 Public members of the Student class C# Programming: From Problem Analysis to Program Design

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

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