Presentation is loading. Please wait.

Presentation is loading. Please wait.

Windows and Web Apps in C# David Figge Session 2 Last Update: 4/11Page 1Copyright (C) 2009 by David Figge. All Rights Reserved.

Similar presentations


Presentation on theme: "Windows and Web Apps in C# David Figge Session 2 Last Update: 4/11Page 1Copyright (C) 2009 by David Figge. All Rights Reserved."— Presentation transcript:

1 Windows and Web Apps in C# David Figge dfigge@uw.edu Session 2 Last Update: 4/11Page 1Copyright (C) 2009 by David Figge. All Rights Reserved.

2 Checkbook Register  Let’s take a look at my solution for the Checkbook Register program… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 2

3 Windows and Web Apps in C# Object Oriented Concepts Last Update: 4/11Page 3Copyright (C) 2009 by David Figge. All Rights Reserved.

4 Object Oriented Concepts  We’ve sort of danced around the concept of objects and classes. I think at this point it would be useful to have an idea as to what we mean by Object Oriented  So what is this Object Oriented stuff?  What’s the alternative?  What’s the big deal?  Let’s talk… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 4

5 A Little History  Computers came into being about 50 years ago  The first ones were very simple  Computers were good at taking a simple task and doing it many times  A first use was missile trajectories  Not surprisingly, code was procedural  Simple steps with loop instructions Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 5

6 A Little History  This was the typical way of programming for the next 30 years  Through the introduction of PCs  Most programming languages used this procedural concept  Assembly, BASIC, C, Forth, Pascal, RPG… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 6

7 Code Example Procedural Example 10. REM Calculate power 20. INPUT “Enter base number: “, B 30. INPUT “Enter power: “, P 40. SET N=B 50. P = P – 1 60. IF P = 0 THEN 90 70. N = N * B 80. GOTO 50 90. PRINT N 100. END Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 7

8 A Little History  In the early 70’s interest started gathering around a few OOP languages  e.g. Smalltalk  This was largely because computers were becoming powerful enough to support the loss of efficiency inherent in more complex languages  C++ was introduced in late 80’s  An object-oriented version of C Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 8

9 Why Object Oriented  OOP was born because the procedural paradigm didn’t relate well to the real world  In general, people don’t interact with subroutines and variables  They interact with ‘objects’.  Entities that, within their own right, can do things and have their own attributes Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 9

10 An Example Situation  Scenario  We want to model traffic on a freeway so we can determine the best exit/entrance locations  Wouldn’t it be nice if they really did this?  Let’s look at this using traditional methodology Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 10

11 Freeway Example (Traditional) 1 1 3 3 2 2 5 5 4 4 6 6 7 7 8 8 Variables Used CarType(8) CarSpeed(8) CarAccel(8) CarBrake(8) CarLoc(8,2) CarOn(8) NumCars Issues: Code is complex, not intuitive, hard to maintain Subs must deal with all cars (adds complexity) What if more cars? Code While (running) for car 1 to 8 if running then NewLoc(CarSpeed(car),CarAccel(car)) DrawCar(CarLoc(car)) end if next car Loop End Sub DrawCar if CarType = 1 then … Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 11

12 Freeway Example (OOP) 1 1 3 3 2 2 5 5 4 4 6 6 7 7 8 8 Car Object Type, accel speed, etc. All kept in object. Object knows how to move and draw itself based on settings inside the object. Advantages: Each car object knows its own type and characteristics Each car object knows how to move itself and draw itself Code and data about the car are together, vastly improving maintenance As a separate entity, one person can work on car object while another works on other parts Code While (running) for each car car.move() car.draw() next car Loop End Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 12

13 OOP In Practice  So a key point to take from this example:  Object Oriented Programming isn’t about rewriting procedural code to use objects  It’s a fundamentally different approach to the problem  With procedural programming  You try to break down the project into tasks  Then each task into bite-sized chunks: functions  In OOP  You determine how objects interact in the real world  Then try to simulate that relationship in the program  By doing that, we more accurately represent the object relationships that exist in the real world.  It’s a fundamentally different approach Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 13

14 Object Oriented Programming  Object Oriented Languages have four characteristics  Inheritance  Encapsulation  Abstraction  Polymorphism Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 14

15 Inheritance  Inheritance is the ability to create one object based on another  Let’s see how this works using animals as an example… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 15

16 Inheritance  Inheritance is the ability to create one object based on another Mammal Characteristics unique to Mammals include live births and having hair on their bodies Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 16

17 Inheritance  Inheritance is the ability to create one object based on another Mammal Canine Because they are derived from mammals, all canines also give live birth and have hair on their bodies. These traits are inherited from the base class “mammal”. The canine class only contains those elements that make canines unique among mammals. For example, they have two ears, four paws, and a snout. Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 17

18 Inheritance  Inheritance is the ability to create one object based on another Mammal Canine Terrier Derived from Canine, Terriers automatically have all characteristics of canines (and therefore mammals). Automatically. The Terrier class only contains those attributes unique to this breed (for example, their size classifications). Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 18

19 Inheritance  Inheritance is the ability to create one object based on another Mammal Canine TerrierGreat Dane Again, Great Danes are derived from Canine (and therefore mammals). They, however, have different characteristics than Terriers (such as their colors). Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 19

20 Inheritance  Inheritance is the ability to create one object based on another Mammal Canine TerrierGreat Dane Inheritance – the ability to base one class on another – simplifies objects and better represents real-world situations. Inheritance is an important aspect of OOP. Let’s discuss and diagram on the board a class hierarchy for our freeway problem… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 20

21 Object Oriented Programming  Object Oriented Languages have four characteristics  Inheritance  Encapsulation  Abstraction  Polymorphism Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 21

22 Encapsulation  Encapsulation is simply the ability to place the code and variables that relate to one another in the same place  In OOP, variables are Attributes, subs/functions are Methods  These terms fit better into the concept of an object.  For example, a car keep its size in a variable, it’s just one attribute of that car.  So the attributes and methods are put together into one unit: an object.  Since we’re here, let’s clarify some additional terms:  Class – The ‘blueprint’ for an object. Defines attributes and methods within used by an object  Object – A specific instantiation of that class in memory Note that I tend to use the terms variables and attributes interchangeably, as well as functions, methods, and subroutines (as they are, technically, the same). Don’t get thrown off by that… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 22

23 Object Oriented Programming  Object Oriented Languages have four characteristics  Inheritance  Encapsulation  Abstraction  Polymorphism Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 23

24 Abstraction  Abstraction (or Data Hiding) is the ability to protect attributes from outside access  May sound minor, but it’s not  It gives the object the ability to control how and when attributes are accessed  A common practice is to make an attribute (class variable) private, and have public methods that set/get them.  This allows the object to validate the data, and perhaps trigger other processes when set/retrieved  Attributes and methods are hidden or shown using the Public and Private keywords. Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 24

25 Object Oriented Programming  Object Oriented Languages have four characteristics  Inheritance  Encapsulation  Abstraction  Polymorphism Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 25

26 Polymorphism  Polymorphism is the ability of a class to override the behavior of a base class. For example  In our car scenario, the base class implementation of the ‘draw’ function could just draw a simple box.  Each car derived from that can override the ‘draw’ function (if desired) to draw a likeness of the car. Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 26

27 Polymorphism  Another aspect of polymorphism is the ability to view objects at multiple levels  This ties into inheritance as well  In our freeway example, we can treat the Honda Accord object as  A Honda Accord  A Honda car  A generic car  A generic vehicle  So, just like in real life, objects can be viewed at various levels  We’ll talk more about this as we cover inheritance in more detail… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 27

28 Object Oriented Programming  So, once again, Object Oriented Languages have four characteristics  Inheritance  Encapsulation  Abstraction  Polymorphism  Questions on our intro to Object Oriented concepts? Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 28

29 Object-Oriented Programming  In many OOP languages, including C# and Java, classes are used to implement the OO principles of Inheritance, Encapsulation, Abstraction, and Polymorphism  In OOP languages, a class defines a type… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 29

30 Objects and Classes  What’s a type?  Data and how it’s stored in memory (e.g. an integer), and  Operations that can be performed using the data object (e.g. +, -, etc.)  What’s a class?  User-defined data type  A class combines data with the operations for manipulating that data  Enables abstraction—the user of the class doesn’t have to know what’s going on inside  What is an object?  An instantiation (variable in memory) of a class  Class is the blueprint, object is the building Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 30

31 What’s this Public and Private?  The public and private keywords control who has access to the data or function  Private means only that class has access to the data or function  Public means anyone can have access to the data or function Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 31

32 Public or Private?  A general rule-of-thumb for public and private variables is as follows:  Class variables are generally private. This ensures that no outside parties change the data without going through proper procedures  Functions used only internally within the class are private also.  Functions available to the ‘outside world’ are public, and constitute the class’ interface.  These functions include functions to get and set appropriate private class variables as well  Let’s look at an example of a class… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 32

33 Employee Class Example  This is a class described using a language called UML  Unified Modeling Language  Classes describe both data and behavior, so after the name of the class we have two sections  The first section describes the data  The second describes the behavior, or methods  The – means private (only the class can access it)  The + means public (everyone can access it) Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 33

34 Employee Class Example  What you see is pretty typical for a class.  Data elements are marked as private  Methods that are part of the class’ public interface are marked public  If there were any “helper” methods, used only internally, they would be private as well  After the data elements, you see a : and the data type used to contain that data (gender:boolean)  After the methods, you see the data type returned from the method (getGender:boolean). Void means none Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 34

35 Employee Class Example  As a final note for this example, you can see that for each data item we have two functions that reference them, a ‘get’ function and a ‘set’ function.  We call these “getters and setters”. They allow access to the data, but only in a controlled way  The Set function can validate the new SSN to validate the format, for example  We’ll talk more about how C# uses properties as getters and setters… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 35

36 Employee Class Example  Since we’re here, a note about object stability  It is the class’ responsibility to make sure that it is always in a valid state for use, even if it is empty  If all classes adhere to this, then the system is always stable  The Getters and Setters help keep this class object stable. Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 36

37 Name: ___________________ Pop Quiz! Question 1 of 4 What is a class? A grouping of data and methods. Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 37

38 Name: ___________________ Pop Quiz! Question 2 of 4 What is the relationship between class functions (methods) and class data members? The methods use the data in order to perform a specific task. Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 38

39 Name: ___________________ Pop Quiz! Question 3 of 4 What is the relationship between an object and a class? An object is an instantiation of a class. A class is a ‘blueprint’ or pattern used to create the object. Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 39

40 Name: ___________________ Pop Quiz! Question 4 of 4 Explain how a class can accomplish abstraction. Using the public and private keywords to restrict outside access to internal data and methods. Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 40

41 Let’s build a Calculator  I’d like to take these concepts we’ve discussed and try them out  Team up with a partner near you and (on paper) identify the objects and relationships involved for a 4-function calculator (add, subtract, multiply, and divide)  So, what objects are in a calculator? How do they interact with one another?  Remember, you don’t need to consider “how will this get coded?”  This would be a computer version of a calculator, made to simulate a desktop calculator.  After you’re done, we’ll translate that class design into code together 10 Minutes Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 41

42 Calculator Example  Okay, so what did you come up with?  Here’s what I came up with… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 42

43 Calculator Example Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 43 Display 123 456 789.0 = + - X / It seems like a pretty key element of a calculator is the display. This object is responsible for taking a number (or string) and displaying it. Equally important would be the number keys. You need to be able to enter numbers! The operation keys take the number you’ve entered, save it, and allow you to enter the other number in the operation. Finally, the = key takes the number saved (by the operator keys) and the current number entered, performs the calculation, and produces a result. Calculator As I looked at the current objects, I felt the relationship between the operators and = key were significant. It makes an simpler design (and one more representative of the real- world) to have a Calculator object (kinda like the CPU). It’s responsible for storing numbers and performing calculations. Note that it’s pretty common to create an object representing a concept (“time”) or more abstract element. Even if it’s just too make an easier design, it’s totally okay. Objects: Display Number keys Operator keys Equals key Calculator Objects: Display Number keys Operator keys Equals key Calculator Ready to build this?

44 Calculator Example  We’re going to build this using Windows Forms  We’ll hit Windows Forms more in depth a little later in the course…  Note that – because of how Windows Forms work – we can’t easily put the buttons in a class together.  We’ll get around this a bit by making them all execute the same code underneath…  Here we go… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 44

45 Calculator Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 45 Calculator Demo…

46 Initializing Member Variables  Problem:  Using a class object with member variables that have not been initialized can cause problems  However, declaring a class variable does not necessarily initialize the member variables  You can initialize variables with =, but that doesn’t work for complex objects or ones that require runtime information to initialize  Using the {... } structure initialization syntax works for classes, but only if all member variables are public  And, as we discussed, that’s hardly ideal…  One solution: You could have a member function that does the initialization  But what if the user of the class forgot to call it? Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 46

47 Constructors  The OOP (and C#) answer to this problem is constructors  Constructors are special member functions whose purpose is to initialize the object into a known stable state.  Constructors have the same name as the name of the class  They don’t have any return type either, as it’s a given that they return an instantiated object of the class  A constructor is always called when the class object is created  If you don’t supply a constructor, the compiler supplies a simple constructor for you  Constructors are typically not private  Somewhat awkward to call it that way… Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 47

48 Constructors  You can have as many constructors as you wish  Normal overloading rules apply  The parameters must change  The constructor with no parameters is called the Default Constructor  Because it is used to initialize the object into its default state (as no values were supplied)  Remember I mentioned if you don’t create a constructor, one is created for you by the compiler  It’s sole purpose is so that you can create an object of that class  It creates a version of the default constructor  It does nothing outside of declared initializations, as it doesn’t know what additional steps to take  If you define any constructors (default or not), the compiler will not define the default constructor for you. Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 48

49 Constructor Exercise Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.  Going back to our Check Register program  From an OOP design standpoint, it would make more sense to have the transaction records be objects, wouldn’t it  That way each transaction knows about it’s transaction type, payee, amount, etc.  It also better represents the real world, where each transaction is an individual entity unto itself.  Let’s work together to create a Transaction class, along with a constructor to initialize it  Then we’ll modify the Main code to use an array of transaction objects rather than using the Trans class…  Ready? Page 49

50 Code Example Transaction Code class Transaction // New Transaction class { TransType type; int checkNum; string payee; decimal amount; DateTime date; public Transaction(TransType trantype, int cknum, string paidto, decimal amt, DateTime dt) { type = trantype; checkNum = cknum; payee = paidto; amount = amt; date = dt; } Transaction[] trnsactns; // In main code module trnsactns = new Transaction[transactions.NumTrans]; for (int x = 0; x < transactions.NumTrans; x++) trnsactns[x] = new Transaction(transactions.GetType(x), transactions.GetCheckNum(x), transactions.GetPayee(x), transactions.GetAmount(x),transactions.GetDate(x)); Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 50

51 Your Turn! Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.  Create a public interface to the Transaction class  Provide Getters and Setters, with the setters validating the input as needed  Check numbers: 0 (if not check transaction), not negative if check transaction  Payee should not be blank unless deposit  Amount must be positive value  Date must be > 2 months ago  Modify your existing code to use the transaction records you just created and the interface you just implemented.  The transactions variable is still used for information about the collection as a whole (like the total number of transactions) Page 51 45 Minutes

52 Windows and Web Apps in C# End of Session 2 Last Update: 4/11Copyright (C) 2009 by David Figge. All Rights Reserved.Page 52


Download ppt "Windows and Web Apps in C# David Figge Session 2 Last Update: 4/11Page 1Copyright (C) 2009 by David Figge. All Rights Reserved."

Similar presentations


Ads by Google