Object-Oriented Programming (part 1 – Data Encapsulation)

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.
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 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
Advanced Object-Oriented Programming Features
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
ASP.NET Programming with C# and SQL Server First Edition
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Syllabus (1) WeekChapters 1Introduction to the course, basic java language programming concepts: Primitive Data Types and Operations 1, 2 2Methods, Control.
1 INF160 IS Development Environments AUBG, COS dept Lecture 13 Title: Classes: Introduction & Review (Extract from Syllabus)
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Chapter Eleven Classes and Objects Programming with Microsoft Visual Basic th Edition.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Microsoft Visual Basic 2008 CHAPTER ELEVEN Multiple Classes and Inheritance.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
C# Programming: From Problem Analysis to Program Design
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Classes, Interfaces and Packages
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.
An Introduction to Programming with C++ Fifth Edition Chapter 14 Classes and Objects.
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.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
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.
Introduction to Object-oriented Programming
Topic: Classes and Objects
Creating Your Own Classes
Classes (Part 1) Lecture 3
INF230 Basics in C# Programming
INF230 Basics in C# Programming
Programming Logic and Design Seventh Edition
Ch 10- Advanced Object-Oriented Programming Features
Advanced Object-Oriented Programming Features
Reference: COS240 Syllabus
Chapter 3: Using Methods, Classes, and Objects
Creating Your OwnClasses
Creating Your Own Classes
Can perform actions and provide communication
Chapter 9 Inheritance and Polymorphism
Can perform actions and provide communication
Corresponds with Chapter 7
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Programming with Microsoft Visual Basic 2008 Fourth Edition
Chapter 9 Objects and Classes
Dr. Bhargavi Dept of CS CHRIST
Can perform actions and provide communication
Outline Anatomy of a Class Encapsulation Anatomy of a Method
CIS16 Application Development and Programming using Visual Basic.net
Object-Oriented Programming
CIS 199 Final Review.
OO Programming Concepts
Lecture 8 Object Oriented Programming (OOP)
Chapter 7 Objects and Classes
Presentation transcript:

Object-Oriented Programming (part 1 – Data Encapsulation) INF230 Basics in C# Programming AUBG, COS dept Lecture 21 Title: Object-Oriented Programming (part 1 – Data Encapsulation) Reference: Doyle, chap 4

Lecture Contents: Components of a class Methods and properties used for object-oriented development Constructors Own instance methods mutators/accessors Call instance methods including mutators and accessors

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

Informal introduction to concept of classes/objects Transition From Structured Programming to OOP From Think in Functions to Think in Objects From Algorithms + Data Structures = Programs To Classes + Objects = Programs

Formal introduction to concept of classes/objects OOP (Object Oriented Programming): Data Encapsulation & Data Hiding Inheritance Polymorphism …

3 main OOP characteristics Data Encapsulation/Data Hiding Data and its routines /named methods/ are said to be encapsulated into a single entity. Data is concealed within a class, so that it cannot be accessed mistakenly from methods outside the class. Inheritance Polymorphism

3 main OOP characteristics Data Encapsulation and Data Hiding Inheritance The process of creating new classes, called derived classes from existing classes or base classes Polymorphism

3 main OOP characteristics Data Encapsulation and Data Hiding Inheritance Polymorphism Generally, the ability to appear in many forms, or in other words Giving different meanings to the same thing More specifically, in OOP it is the ability to redefine methods for derived classes

3 main OOP characteristics Data Encapsulation and Data Hiding Inheritance Polymorphism And many other, e.g. Abstract classes Interfaces …

The Object Concept Solution is 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

Class SmallObj - definition { private int somedata; public int getSomeData() { return somedata; } public void setSomeData(int d) { somedata = d; } public void ShowData() Console.WriteLine("\n\nData is = {0}", somedata); } } // end of class

Class SmallObj – how to use? static void Main(string[] args) { SmallObj a = new SmallObj(); a.setSomeData(713); Console.WriteLine(" {0}", a.getSomeData() ); a.ShowData(); . . . Console.ReadKey(); }

Anatomy of a Class Class components: Member data /fields/ Methods Constructors Accessors / Mutators In stance Methods and Class Methods Properties Events

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; … C# Programming: From Problem Analysis to Program Design

Private Member Data (continued) public class CarpetCalculator { private double pricePerSqYard; private double noOfSqYards; … C# Programming: From Problem Analysis to Program Design

Anatomy of a Class Class components Methods: Constructors

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 Also do not include keyword void Constructors use same identifier (name) as class Constructors use public access modifiers C# Programming: From Problem Analysis to Program Design

Constructor (cont.) 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 C# Programming: From Problem Analysis to Program Design

Constructor (continued) public access modifier is always associated with constructors //Default constructor public Student ( ) { } //Constructor with one parameter public Student (int sID ) studentNumber = sID; C# Programming: From Problem Analysis to Program Design

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 C# Programming: From Problem Analysis to Program Design

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

Accessors Getters Returns the current value Standard naming convention → prefix with “Get” Accessor for noOfSquareYards public double GetNoOfSqYards( ) { return noOfSqYards; } Properties serve purpose Accessor C# Programming: From Problem Analysis to Program Design

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) // length, width – in feet; 1 yard = 3 feet; 1 sq.yard = 9 sq.feer noOfSquareYards = length * width / 9; Overloaded Mutator C# Programming: From Problem Analysis to Program Design

Other Instance Methods No need to pass arguments to these methods – Defined in the same class as the data members Instance methods can directly access private data members Define methods as opposed to storing values that are calculated from other private data members public double CalculateAverage( ) { return (score1 + score2 + score3) / 3.0; } C# Programming: From Problem Analysis to Program Design

Anatomy of a Class Class components: Properties

Property Can replace accessors and mutators Properties look 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 // given data member noOfSqYards. See the property NoOfSqYards below: public double NoOfSqYards { get return noOfSqYards; } set noOfSqYards = value; C# Programming: From Problem Analysis to Program Design

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

Property (continued) If an instantiated object is named berber, to get value of data member associated to /i.e. hidden behind/ the property NoOfSqYards, write: double var; var = berber.NoOfSqYards; Console.WriteLine(“{0}”, berber.NoOfSqYards); C# Programming: From Problem Analysis to Program Design

Property (continued) Given a class Employee and data member salary private decimal salary; See the property Salary below: If an instantiated object is named peter, to update /i.e. modify – increase or decrease/ value of data member salary associated to /i.e. hidden behind/ the property Salary, write: peter.Salary = peter.Salary + 1500.0M; peter.Salary -= 1500.0M; C# Programming: From Problem Analysis to Program Design

Anatomy of a Class Class components: Inheritance relation and access to base class methods

ToString( ) Method All user-defined classes inherit four methods from the object class ToString( ) Equals( ) GetType( ) GetHashCode( ) C# Programming: From Problem Analysis to Program Design

ToString( ) Method ToString( ) method is called automatically by several methods Write( ) WriteLine( ) methods Can also invoke or call the ToString( ) method directly C# Programming: From Problem Analysis to Program Design

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 C# Programming: From Problem Analysis to Program Design

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"); } C# Programming: From Problem Analysis to Program Design

ToString( ) method 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

Anatomy of a Class Calling methods

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( ) C# Programming: From Problem Analysis to Program Design

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); C# Programming: From Problem Analysis to Program Design

Constructor (continued) Default values are assigned to variables of the value types when no arguments are sent to constructor 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

Calling Accessor and Mutator Methods Method name is preceded by the object name Calling mutator method berber.SetNoOfSquareYards(27.83); Calling accessor method Console.WriteLine("{0:N2}", berber.GetNoOfSquareYards( )); C# Programming: From Problem Analysis to Program Design

Using property instead of mutator methods Method name is preceded by the object name berber.SetNoOfSquareYards(27.83); If property defined, can use property instead of mutator methods PropertyName = value; // Acts like mutator here NoOfSquareYards = 27.83; C# Programming: From Problem Analysis to Program Design

Using property instead of accessor methods Method name is preceded by the object name Console.WriteLine("{0:N2}", berber.GetNoOfSquareYards( )); If property defined, can use property instead of accessor methods Console.WriteLine("{0:N2}", berber.NoOfSquareYards); // Property Acts like accessor here C# Programming: From Problem Analysis to Program Design

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. C# Programming: From Problem Analysis to Program Design

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

User classes and Test class using System; namespace MyUserClasses { public class Student } //===================================== namespace TestUserClasses using MyUserClasses; class Test public static void Main()

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 C# Programming: From Problem Analysis to Program Design

Testing Your New Class Figure 4-7 Output from Carpet example using instance methods C# Programming: From Problem Analysis to Program Design

How to create a class By hand – typing all the source text concerning the class template – as it was done with SmallObj class Using a number of tools available in Visual Studio to aid in the development of applications To add a second class in your application, use the PROJECT menu or Solution Explorer window

Add a Class Use the PROJECT menu or the Solution Explorer Window Select your project file, then 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

Open the Class Diagram from Solution Explorer, View Class Diagram Figure 4-1 Student class diagram created in Visual Studio C# Programming: From Problem Analysis to Program Design

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 C# Programming: From Problem Analysis to Program Design

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 C# Programming: From Problem Analysis to Program Design

Practical exercises .

Class SmallObj Modify the SmallObj class: Ignore ShowData() method as unnecessary Define property SOMEDATA associated with somedata field Demonstrate how to use the property. SmallObj a = new SmallObj(); a.SOMEDATA = 5555; Console.WriteLine("\n\n\n{0}", a.SOMEDATA);

Class SparePart Develop a class with data members – fields: int modelno, int partno, double cost And Constructors No arg, 3-arg Accessor/Mutator methods Properties Modelno Partno Cost

Class Counter Develop a class with data members – fields: int count And Constructors No arg, 1-arg Accessor/Mutator methods Property Count

Class Distance Develop a class with data members – fields: int feet double inches Constructors No arg, 1-arg (2 copies), 2-arg Accessor/Mutator methods Properties Feet Inches

Class Point Develop a class with data members – fields: int xcoord int ycoord Constructors No arg, 2-arg Accessor/Mutator methods Properties Xcoord Ycoord

Class Circle Develop a class with data members – fields: int xcoord int ycoord double radius Constructors No arg, 3-arg Accessor/Mutator methods Properties Xcoord Ycoord Radius

Thank You For Your Attention!

RealEstateInvestment Example Figure 4-8 Problem specification for RealEstateInvestment example C# Programming: From Problem Analysis to Program Design

Data for the RealEstateInvestment Example Table 4-2 Instance variables for the RealEstateInvestment class C# Programming: From Problem Analysis to Program Design

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

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