1 / 50

242-210 F II

242-210 F II. Semester 2 , 2012-2013. Objectives explain classes and objects introduce fields, constructors, and methods go through two examples. 3 . Classes and Objects. Original Slides by Dr. Andrew Davison. Topics. 1. What are Classes, Objects? 2. The Contents of a Class

oprah-cook
Download Presentation

242-210 F II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 242-210 F II Semester 2, 2012-2013 • Objectives • explain classes and objects • introduce fields, constructors, and methods • go through two examples 3. Classes and Objects Original Slides by Dr. Andrew Davison

  2. Topics 1. What are Classes, Objects? 2. The Contents of a Class 3. A Stack Class 4. Creating a Stack Object 5. Understanding a Stack Object 6. A Bad Stack Interface 7. Good vs. Bad Interfaces 8. Creating Two Stack Objects 9. Object Types vs. Primitive Types 10. A Ticket Machine

  3. 1. What are Classes, Objects? • A class is a factory for objects. • e.g. a Car class is a factory for Car objects • A Car class is not a Car object • e.g. a Car factory is not the Cars it makes Car class Car objects

  4. Very Important Slide • A class consists of data (fields) and methods. • Each object gets a copy of the class's data (fields). • An object uses the methods stored in the class • the class is a kind of method library for all of its objects

  5. A Class Involves at least 2 People • A class is implemented by one person. • A class is used by other, different people. • The implementor wants to make a class that is easy to use. • A user does not care how a class is implemented. He only wants to know the operations that it can carry out (its interface).

  6. A Class for a Stack push pop • This interface helps the implementor decide on the class's operation/methods. Other operations: isEmpty topOf A Stack (of plates)

  7. 2. The Contents of a Class public class ClassName { Fields // variables used by all methods Constructor(s) // method(s) that initialize an object Methods (functions) } 3 main parts of a class

  8. Fields • Fields are the variables (data) used by an object. • Also known as instance variables. public class Stack { private int store[]; private int max_len; private int top; // all methods can use fields } type visibility variable name private int top;

  9. Constructors • A constructor is a special method which initializes an object's fields. • A constructor has the same name as the class. public Stack(int size) { store = new int[size]; max_len = size-1; top = -1; }

  10. Methods • Methods are functions very like C/C++ functions/methods. • The methods that are visible to the user (public) in a class depend on the interface of the thing being implemented • e.g. the stack interface → public methods that a user can call

  11. 3. A Stack Class // Stack.java// Written by the Stack implementorpublic class Stack {private int store[]; // hidden dataprivate int max_len;private int top;public Stack(int size) // visible method { store = new int[size]; max_len = size-1; top = -1; } : continued

  12. public boolean push(int number) { if (top == max_len) return false; top++; store[top] = number; return true; } : continued

  13. public boolean pop() { if (top == -1) return false; top--; return true; } public int topOf() { return store[top]; } public boolean isEmpty() { return (top == -1); }} // end of Stack.java

  14. Stack Class Diagram class name fields methods constructor '-' means private '+' mean public

  15. 4. Creating a Stack Object // TestStack.java// Written by the Stack userimport java.io.*;public class TestStack { public static void main(String args[]) { Stack stk1 = new Stack(10); stk1.push(42); stk1.push(17); stk1.pop(); System.out.println(“Top value is “ + stk1.topOf() ); }} hello object!!

  16. Compilation and Execution $ javac Stack.java$ javac TestStack.java$ java TestStackTop value is 42 Stack.class is in the same directory as TestStack.class.

  17. Notes • The user cannot directly access the object's data (fields) because it is private. • The user can call methods because they are public • the methods are the object's user interface continued

  18. Object creation: Stack stk1 = new Stack(10) has three parts: Stack stk1 // create a variable name, stk1 = new // create a Stack object Stack(10) // call the constructor to initialize the object state

  19. Stack Object Diagram Just after object creation: private means the user of the object cannot directly access the fields. stk1 0 1 2 9 . . . . store[] max_len 9 -1 top The stack object has a copy of the class' fields (data), but uses themethods in the 'class library'.

  20. Meaning of a method call: • stk1.push(17) means call the push() method stored in the Stack class, but apply it to the stk1 object • Methods work on an object's fields even though the methods are stored in the class.

  21. Stack Object Diagram (later) Just before the call to pop(): stk1 . . . . store[] 42 17 max_len 9 1 top

  22. 5. Understanding a Stack Object • What does the user need to understand in order to use a Stack object? • He only needs to understand the interface • e.g. push pop isEmptytopOf 17 42 continued

  23. The user does not need to know how things are implemented • the user is happy since the interface is simple • the implementor is happy since he can change the implementation (e.g. make it faster), and the user will not complain (so long as the interface does not change)

  24. 6. A Bad Stack Interface //BadStack.java// Written by the ฺBadStack implementorpublic class BadStack {private int store[]; private int max_len;public int top; // constructor and methods same as in Stack :

  25. Creating a BadStack Object // TestBadStack.java// Written by the BadStack userimport java.io.*;public class TestBadStack { public static void main(String args[]) { BadStack stk1 = new BadStack(10); stk1.push(42); stk1.push(17);stk1.top = 0; stk1.pop(); System.out.println(“Top value is “ + stk1.topOf() ); }} hello object!! ?

  26. Understanding the BadStack Object • What does the user need to understand in order to use the BadStack object? • He needs to understand the interface and implementation • e.g. push pop + store[], top, max_len 17 42

  27. 7. Good vs Bad Interfaces • A good interface hides the class's implementation • all fields are private • A good interface can be visualized by the user (e.g the stack diagram) • A good interface has easy-to-understand public methods.

  28. Kinds of Methods in an Interface • Aside from the constructor, most public methods can be grouped into two types: • accessor (get) methods • they return information to the user • e.g. in Stack: isEmpty(), topOf() • mutator (set) methods • they change the object's state (its fields) • e.g. in Stack: push(), pop()

  29. An Accessor (Get) Method return type visibility modifier method name parameter list (usually empty) public int topOf() { return store[top]; } return statement start and end of method body (block)

  30. A Mutator (Set) Method return type visibility modifier method name parameter(s) public boolean push(int number) { if (top == max_len) return false; top++; store[top] = number; return true; } fields being mutated

  31. 8. Creating Two Stack Objects • Many objects can be created from a class: :// in main() of TestStackStack stk1 = new Stack(10);Stack stk2 = new Stack(20);stk1.push(27);stk1.push(13);stk2.push(10);el = stk2.topOf(); : create two objects

  32. Stack Objects Diagrams stk1 . . . . store[] 27 13 max_len 8 1 top Just before the call to topOf(): . . . . stk2 store[] 10 max_len 19 0 top

  33. Notes • The two objects have two copies of the class's data • changes in one object do not affect the other object • Both objects use the methods in the class • stk1.push(13) means call push() and apply it to the data inside stk1

  34. 9. Object Types vs. Primitive Types Foo object a Foo a = new Foo(); object type primitive type 32 int i; i = 32; i Primitive types include: int, float, double, char, byte

  35. Assignment Differences Foo a = new Foo(); Foo b; b = a; copy the link (the reference) a b Foo object int a = 32; int b; b = a; copy the value 32 32 a b

  36. 10. A Ticket Machine show balance (the amount of money entered) • The required interface helps the implementor decide on the class’s methods. show price (and other info) print ticket insert money give change

  37. 10.1. Class Diagram accessor methods accessor/mutator methods (tricky to understand) mutator method constructor

  38. 10.2 Ticket Machine Class public class TicketMachine { private int price; // price of a ticket private int balance; // amount entered by customer private int total; // total money in machine public TicketMachine(int ticketCost) { price = ticketCost; // set the ticket price balance = 0; total = 0; } continued

  39. public int getPrice() { return price; } public int getBalance() { return balance; } public int getTotal() { return total; } continued

  40. public void insertMoney(int amount) // process money inserted into the machine { if (amount > 0) balance = balance + amount; else System.out.println("Use a positive amount: " + amount); } continued

  41. public void printTicket() { if (balance >= price) {// if enough money inserted // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# Ticket"); System.out.println("# " + price + " baht."); System.out.println("##################"); System.out.println(); // Update the total collected with the price. total = total + price; // Reduce the balance by the prince. balance = balance - price; } else // report error System.out.println( "You must insert at least: " + (price - balance) + " more baht."); } // end of printTicket() continued

  42. public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; //clear ticket machine's balance return amountToRefund; //return balance amount } } // end of TicketMachine class

  43. 10.3. Local Variables • Fields are one sort of variable • they store values through the life of an object • they are accessible by all the methods • Methods can include shorter-lived variables: • they exist only as long as the method is being executed • they are only accessible from within the method

  44. Local Variable Example A local variable public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; } No visibility modifier

  45. 10.4. Using a TicketMachine Object public class TMDemo { public static void main(String[] args) { TicketMachine tm = new TicketMachine(10); // tickets cost 10 System.out.println("Ticket price: " + tm.getPrice()); System.out.println("Current total: " + tm.getTotal()); System.out.println("Insert 5 baht"); tm.insertMoney(5); :

  46. System.out.println("Insert 10 baht"); tm.insertMoney(10); System.out.println("Current balance: " + tm.getBalance()); tm.printTicket(); System.out.println("Current balance: " + tm.getBalance()); System.out.println("Current total: " + tm.getTotal()); :

  47. System.out.println("Request Change"); System.out.println("Change is: " + tm.refundBalance()); System.out.println("Current balance: " + tm.getBalance()); } // end of main() } // end of TMDemo class

  48. Compilation $ javac TicketMachine.java$ javac TMDemo.java TicketMachine.class is in the same directory as TMDemo.class.

  49. Output of java TMDemo Ticket price: 10 Current total: 0 Insert 5 baht Insert 10 baht Current balance: 15 ################## # Ticket # 10 baht. ################## Current balance: 5 Current total: 10 Request Change Change is: 5 Current balance: 0

  50. TicketMachine Object Diagram Just after object creation: tm price 10 0 balance 0 total The TicketMachine object has a copy of the class' data, but uses the methods in the 'class library'.

More Related