Download presentation
Presentation is loading. Please wait.
1
Traditional (non-object-oriented) Programming based on an algorithmic approach with programs consisting of lines of code organized around various programming structures such as loops/if..then..else/goto Lots of code Flow charts as design tool, spaghetti code
2
Structured programming Code using well defined program structures to avoid spaghetti code Structures: single entry, single exit, no goto Top-down programming using functions and procedures. Code would be organized into modules or groupings of functions, with a typical large program having many modules (each with a.h file) and carefully specified rules for using the functions.
3
Data Structures Typical program would define data structures (variables, arrays, structs ) to model the situation. Usually these would be in some global context. Although frequently defined in code modules, would in fact be one global context. Some data structures might have special functions to handle them, like adding to a list, but often these would be specific to the particular kind of structure in the program. Code, in general, would act on the data structures to produce the application. Data Structures would be very application specific, as a rule.
4
Pig Game Game of Pig 2 players, one pair of dice Object: Be the first player to accumulate a total of 100 points by rolling the dice. The play: A. Players alternate turns attempting to accumulate points. B. A turn consists of 1 or more rolls of the dice and the points are accumulated. C. When a turn ends, accumulated points are added to the game total for that player. D. If on any roll of a turn, one of the dice is a 1, then all points accumulated on that turn are forfeit, and the turn ends. E. If the player rolls snake-eyes (two 1's) then the player loses all points for the round and all points accumulated in the game, and the turn ends. F. The player may choose to end a turn and pass the dice at any point after the first roll or may be a Pig and roll again. Variation for computer play: F1: the computer must pass the dice if it accumulates 20 points or more on a turn, but it must otherwise roll the dice if possible (subject to rules D and E)
5
Data Structures Begin by defining data structures (variables). int humanscore=0; int humanroundtotal; //other vars to describe human int computerscore=0 //other vars for computer int computerroundtotal; //Dice variables. int die1, die2; int rollTotal;
6
Code manipulates the data while(humanscore < 100 && computerscore < 100) { //human turn while (turnNotOver) { //roll dice (die1=RollDie(); die2=RollDie()l; //process roll (update variables like humanroundtotal) //display result //if allowed by rules to continue then ask //if not continuing then update score // turnNotOver=false; } //if human hasn't won then computer turn //similar code but instead of asking we just check the round total } Each pseudo-code line might be a function (method).
7
Some difficulties Namespaces …. Hard to guarantee unique variable names especially with multiple programmers contributing Reusability …. Hard to reuse code since everything became tended to be special purpose. Reuse ideas…’borrow’ code and make changes for your app Maintainability.. Logical relationships often difficult to piece together. Code can be hard to understand and modify.
8
Coding Standards Depended a lot on coding standards within an organization. Variable naming schemes, coding formats, types of functions defined for particular uses, how files were accessed, database usage, documentation.
9
Object-Oriented approach Begin by analyzing the problem and identifying candidates for Objects. Example: Die PairOfDice PigGame PigPlayer The variables and data structures of the traditional programming are replaced by 'state' variables within the classes. Example: each player keeps track of his score, and dice know how to roll themselves.
10
Code Structure Instead of code modules of 'helper' functions to manipulate the variables, each Object has it's own methods to implement behaviors of the Object. Structure defined in diagrams…relationship between objects, and scenarios…how objects interact The overall program structure will typically be defined in one of the methods in some top-level class...e.g. the PigGame class might have a controlling method called play.
11
Old style coding int rollDie(void) { return (int) (Math.random() * numFaces) + 1; } //Usage: // int die; data structure //die = rollDie();
12
Object Based newpiggame\Die.java newpiggame\PairOfDice.java
13
Objects Objects have state and behavior –Example: String for example: "this is a String object" –State is usually hidden, accessed by operations state: the actual characters operations: length/toUpperCase/indexOf() etc
14
Figure 5.1 A String object (for “Java is fun” ) length () indexOf(‘a’) toUpperCase()// other services
15
Figure 5.2 A String object (for “JAVA IS FUN” ) length () indexOf(‘a’) toLowerCase()// other services
16
public char charAt(int index)character at the specified index public int compareTo(String anotherString) 0 if equal to anotherString negative if less positive if greater public boolean equals(Object anObject)true for equal Strings public int indexOf(char ch)index of first occurrence of ch public int indexOf(char ch, int from)index of first occurrence of ch starting at index from public int indexOf(String str)index of first occurrence of str public int indexOf(String str, int from)index of first occurrence of str starting at index from public int length()string length Figure 5.3 Selected String methods(1)
17
public String substring (int beginIndex, int endIndex) new string with characters from beginIndex to endIndex – 1 public String toLowerCase()returns a lowercase string public String toUpperCase()returns an uppercase string public String trim()removes leading and trailing whitespaces public static String valueOf(int i)creates a string from an int public static String valueOf(double d)creates a string from a double Figure 5.3 Selected String methods(2)
18
MethodReturn valueDescription of return value s.charAt(6)‘e’‘e’The character at position 6 is an ‘e.’ s.compareTo(“Toast”)negative integerThe string referred to by s is alphabetically less than “Toast” so the return value is a negative integer. s.equals(“Java is fun”)falseThe string referred to by s does not have the same characters as “Java is fun” s.indexOf(‘e’)6The leftmost ‘e’ on the string occurs at index 6. s.indexOf(‘e’,8)15The first occurrence of ‘e,’ starting from index 8, is at index 15. s.indexOf(“us”)10The leftmost occurrence of “us” starts at index 10. Figure 5.4 Examples of string methods(1)
19
MethodReturn valueDescription of return value s.indexOf(“us”,11)13The first occurrence of “us”, starting from index 11, begins at index 13. s.indexOf(“us”,15)There is no occurrence of “us” staring at index 15. s.length()27This string contains 27 characters. s.substring(13,24)A new String with characters “use objects.” The string “use objects.” starts at index 13 and continues up to index 24. s.toLowerCase()A new String with characters “java let us use objects. ” Returns a new string with all lowercase characters. s.toUpperCase()A new String with characters “JAVA LET US USE OBJECTS. ” Returns a new string with all uppercase characters. s.trim()A new String with characters “Java lets us use objects.” Returns a new string with leading and trailing blanks removed Figure 5.4 Examples of string methods(2)
20
Object types vs Java Classes Objects types are implemented using Java Classes. Objects are then instances of a Java class.
21
Java Class instance variables - or fields Instance Methods - refer to a specific instance of the object class
22
Variables Values vs. Reference int x = 4; //x corresponds to a location containing the value 4 String s = "this is a String object"; //s corresponds to a location containing a ref (or pointer) to the actual object.
23
Object variables A ref (or object variable) is null until it is instantiated, usually with the new operator.
24
Figure 5.5 Value vs. reference 4 x my String “We want a big car” a. x holds a valueb. myString holds a reference
25
Figure 5.6 Assignment of an integer 45 44 xy xy int x = 4, y = 5; Y = x;
26
st st “soup”“fish” “soup”“fish” String s = “soup”, t = “fish”; t = s; Figure 5.7 Assignment of a string
27
s null Figure 5.8 An object declaration without object creation
28
house s1 s4 s2 Figure 5.9 s1 == s4 but s1 != s2
29
UML Objects are often modeled using UML (or universal modelling language)
30
Figure 5.10 The BankAccount class BankAccount balance: double getBalance deposit withdraw
31
Figure 5.11 The revised BankAccount class BankAccount balance: double BankAccount() BankAccount(initialAmount: double) getBalance(): double Deposit(amount: double): void withdraw(amount: double): void
32
Figure 5.12 Result of new BankAccount() :BankAccount Balance = 0.0 getBalance Deposit withdraw
33
Figure 5.13 my Account refers to a new BankAccount :BankAccount Balance = 0.0 getBalance Deposit withdraw myAccount
34
Figure 5.14 An object declaration without object creation myAccount null
35
transactions Acct class balance myAcct object balance yourAcct object Figure 5.15 The difference between class and instance variables
36
CustomerWaiter Cook Figure 5.16 A class diagram
37
aCustomer Figure 5.17 A sequence diagram for a food order aWaiteraCook take order make burger serve soda make fries serve burger serve fries pay
38
aCustomer Figure 5.18 A revised sequence diagram for a food order aWaiteraCook take order make burger serve soda make fries serve burger serve fries place order take soda order take fries order done pay
39
Figure 5.19 Fields for the Name, Address and Person class(1) Name private String first private char initial private String last public Name(String f, String l) public Name(String f, char i, String l) public String toString() Address private String street private String city private String state private String zip public Address(String st, String cy, String se, String zp) public String toString()
40
Figure 5.19 Fields for the Name, Address and Person class(2) Person private String id private Name name private Address address public Person(String i, Name a, Address a) public String getId() public String toString()
41
Person id: String name: Name address: Address Name first: String initial: char last: String Address id: String name: Name address: Address zip: String Figure 5.20 Composition: the Name, Address and Person class
42
:Name first: “Wolfgang” initial: ‘A’ last: “Mozart” Figure 5.21 An instance of Name composer
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.