Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Lecture 4 CS 1311X Have a Coke! 13 X 11. Take the Survey!

Similar presentations


Presentation on theme: "Java Lecture 4 CS 1311X Have a Coke! 13 X 11. Take the Survey!"— Presentation transcript:

1 Java Lecture 4 CS 1311X Have a Coke! 13 X 11

2 Take the Survey! http://www.coursesurvey.gatech.edu

3 Today's Lecture brought to you with the kind assistance of...

4 13 X 11 Juicing Up the Coke Machine Adding cash –More methods Adding setup flexibility –Constructors Adding a serial number –Class vs instance variable –Class vs instance methods Inheritance –Reuse/Ease of maintenance Adding more flavors –Arrays

5 13 X 11 The story so far... class CokeMachine { private int numCans = 3; public void vend() { if(numCans > 0) { System.out.println("Have a coke!"); numCans--; } else { System.out.println("Sorry, no Cokes."); }

6 13 X 11 The story so far... // class CokeMachine (continued) public void load(int n) { numCans += n; System.out.println("Loaded with " + numCans); }

7 13 X 11 Issues How many cans can the machine hold? Should the CokeMachine print things out? Want to be able to vary initial number of cans Want to give machine a name Want to have a serial number Want more variety (Mr. Pibb?)

8 13 X 11 How many cans can the machine hold? class CokeMachine { private int numCans = 3; private int maxCans = 60; public void vend() { if(numCans > 0) { System.out.println("Have a coke!"); numCans--; } else { System.out.println("Sorry, no Cokes."); } } // vend

9 13 X 11 How many cans can the machine hold? // class CokeMachine (continued) public void load(int n) { int temp = numCans + n; if(temp > maxCans) { System.out.println("Attempt to overload"); numCans = maxCans; } else { numCans = temp; System.out.println("Loaded with " + numCans); } // load } // CokeMachine

10 13 X 11 Should the Machine print things out? class CokeMachine { private int numCans = 3; private int maxCans = 60; public boolean vend() { if(numCans > 0) { numCans--; return true; } else { return false; }

11 13 X 11 Should the Machine print things out? public int load(int n) { // Will return number of cans loaded int retval; int temp = numCans + n; if(temp > maxCans) { retval = maxCans - numCans; numCans = maxCans; } else { retval = n; numCans = temp; } return retval; } // load

12 13 X 11 Testing Using a test Main // Static method for testing coke machines public static void vendNCokes(int n, CokeMachine cm) { for(int i=0; i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/9/2554271/slides/slide_12.jpg", "name": "13 X 11 Testing Using a test Main // Static method for testing coke machines public static void vendNCokes(int n, CokeMachine cm) { for(int i=0; i

13 13 X 11 Testing Using a test Main public static void main(String args[]) { CokeMachine cokeM; cokeM = new CokeMachine(); vendNCokes(5, cokeM); System.out.println("Tried to load 30 actually " + cokeM.load(30)); vendNCokes(5, cokeM); System.out.println("Tried to load 60 actually " + cokeM.load(60)); } // main } // CokeMachine

14 13 X 11 Result >javac CokeMachine.java >java CokeMachine Coke! Coke! Coke! Empty Empty Tried to load 30 actually 30 Coke! Coke! Coke! Coke! Coke! Tried to load 60 actually 35 >

15 13 X 11 Vary initial number of cans Often it's necessary of perhaps desireable to initialize variables in the object. Java allows the programmer to write special initialization modules called constructors A constructor can only be run once, automatically at the time the object is created using the new operator

16 13 X 11 Adding a Constructor class CokeMachine { private int numCans; private int maxCans; // Constructor public CokeMachine(int num, int max) { numCans = num; maxCans = max; } Using a constructor: CokeMachine cm; cm = new CokeMachine(3, 60); Using a constructor: CokeMachine cm; cm = new CokeMachine(3, 60);

17 13 X 11 What happened? >javac CokeMachine.java CokeMachine.java:51: No constructor matching CokeMachine() found in class CokeMachine. cokeM = new CokeMachine(); ^ 1 error Was there a constructor that looked like: public CokeMachine()

18 13 X 11 The Mysterious Default Constructor Java automatically supplies a constructor to any class that doesn't have one. It's cleverly known as the default constructor. It looks like this:

19 13 X 11 The Mysterious Default Constructor Well actually it's invisible but if you could see it then it would look like this: public CokeMachine() { }

20 13 X 11 So where did it go? Java giveth... Java taketh away... As soon as you define any constructor the default constructor no longer exists. Why?

21 13 X 11 But I want one! class CokeMachine { private int numCans; private int maxCans; // Constructor public CokeMachine(int num, int max) { numCans = num; maxCans = max; } public CokeMachine() { numCans = 3; maxCans = 60; }

22 13 X 11 You could even do this class CokeMachine { private int numCans; private int maxCans; // Constructor public CokeMachine(int num, int max) { numCans = num; maxCans = max; } public CokeMachine() { /* Note that numCans and maxCans are not initialized */ }

23 13 X 11 So you would need these... // class CokeMachine (continued) public setNumCans(int n) { numCans = n; } public setMaxCans(int n) { maxCans = n; } Methods which modify the value of variables inside of the object or class are known as modifiers.

24 13 X 11 You could also write these... // class CokeMachine (continued) public int getNumCans() { return numCans; } public int getMaxCans() { return maxCans; } Methods which return the value of variables inside of the object or class are known as accessors.

25 13 X 11 Notice the parameter names class CokeMachine { private int numCans; private int maxCans; // Constructor public CokeMachine(int num, int max) { numCans = num; maxCans = max; }

26 13 X 11 We want... To name the parameters numCans maxCans Why? Two reasons –Documentation –Nature of CS Guys

27 13 X 11 Documentation

28 13 X 11 Typical CS Geeks Guys

29 13 X 11 Typical CS Geeks Guys Heh, heh... My high score in Space Invaders was 257,368

30 13 X 11 Typical CS Geeks Guys I wonder if Java Beans will give me gas?

31 13 X 11 Typical CS Geeks Guys I wonder how much of a curve there will be in CS 1311X?

32 13 X 11 Writing like the big kids... class CokeMachine { private int numCans; private int maxCans; // Constructor public CokeMachine(int numCans, int maxCans) { this.numCans = numCans; this.maxCans = maxCans; } public CokeMachine() { numCans = 3; maxCans = 60; }

33 13 X 11 Writing like the big kids... class CokeMachine { private int numCans; private int maxCans; // Constructor CokeMachine public CokeMachine(int numCans, int maxCans) { this.numCans = numCans; this.maxCans = maxCans; } public CokeMachine() { this this(3, 60); } Constructor Chaining

34 13 X 11 How do it know? Java differentiates constructors using the parameter list CokeMachine() CokeMachine(int, int) Note: Same idea works for methods

35 13 X 11 Lots of flexibility class CokeMachine { private int numCans; private int maxCans; private String name; CokeMachine public CokeMachine(String name, int numCans, int maxCans) { this.numCans = numCans; this.maxCans = maxCans; this.name = name; }

36 13 X 11 Lots of flexibility // class CokeMachine (continued) CokeMachine public CokeMachine(String name) { this(name, 3, 60); } public CokeMachine(String name, int numCans) { this(name, numCans, 60); } public CokeMachine(int maxCans, String name) { this(name, 3, maxCans); } public CokeMachine(int numCans, int maxCans) { this("unnamed", numCans, maxCans); }

37 13 X 11 Let's not get carried away! // class CokeMachine (continued) CokeMachine public CokeMachine(int numCans) { this("unnamed", numCans, 60); } public CokeMachine(int maxCans) { this("unnamed", 3, maxCans); }

38 13 X 11 Lots of flexibility // class CokeMachine (continued) CokeMachine public CokeMachine(String name) { this(name, 3, 60); } public CokeMachine(String name, int numCans) { this(name, numCans, 60); } public CokeMachine(int maxCans, String name) { this(name, 3, maxCans); } public CokeMachine(int numCans, int maxCans) { this("unnamed", numCans, maxCans); }

39 13 X 11 Why so many constructors? User convenience CS 1312

40 13 X 11 Recall Kurt's Dream class CokeMachine { private int numCans; private int maxCans; private String name;... } CokeMachine Object numCans = ___ maxCans = ___ name = ___ CokeMachine Object numCans = ___ maxCans = ___ name = ___ CokeMachine Object numCans = ___ maxCans = ___ name = ___ CokeMachine Object numCans = ___ maxCans = ___ name = ___

41 13 X 11 Want to have a serial number? Change in requirements Each machine should have a serial number Will need to keep track of how many machines have been created Where to keep a variable that keeps track of the number of machines? Encapsulation???

42 13 X 11 Adding a Serial Number class CokeMachine { private int numCans; private int maxCans; private String name; private int serial; private static int count = 0; CokeMachine public CokeMachine(String name, int numCans, int maxCans) { this.numCans = numCans; this.maxCans = maxCans; this.name = name; count++; serial = count; } Note: Since we used constructor chaining all the other constructors still work!

43 13 X 11 Recall Kurt's Dream class CokeMachine { private int numCans; private int maxCans; private String name; private int serial; private static int count = 3;... } CokeMachine Object numCans = 3 maxCans = 60 name = "CoC" serial = 1 static count CokeMachine Object numCans = 3 maxCans = 60 name = "CoC" serial = 3 static count CokeMachine Object numCans = 3 maxCans = 60 name = "CoC" serial = 2 static count

44 13 X 11 Static vs. Instance Variables that "live" in the class: Static or Class Variables Variables that "live" in the object: Instance Variables We can (and typically must) have corresponding methods

45 13 X 11 Examples class SimpCokeMach { int numCans int serial; static int count = 0; public SimpCokeMach() { numCans = 10; count++; serial = count; }

46 13 X 11 Examples // class SimpCokeMach (continued) public int getNumCans() { return numCans; } public int getSerial() { return serial; } public int getCount() { return count; }

47 13 X 11 Examples // class SimpCokeMach (continued) public static void main(String args[]) { SimpCokeMach scm1 = new SimpCokeMach(); SimpCokeMach scm2 = new SimpCokeMach(); System.out.println(scm1.getNumCans()); System.out.println(scm2.getNumCans()); System.out.println(scm1.getMaxCans()); System.out.println(scm2.getMaxCans()); System.out.println(getCount()); }

48 13 X 11 Examples // class SimpCokeMach (continued) public int getNumCans() { return numCans; } public int getSerial() { return serial; } public static int getCount() { return count; }

49 13 X 11 Examples class STester { public static void main(String args[]) { SimpCokeMach scm1 = new SimpCokeMach(); SimpCokeMach scm2 = new SimpCokeMach(); System.out.println(scm1.getCount()); System.out.println(scm2.getCount()); System.out.println(SimpCokeMach.getCount()); }

50 13 X 11 Universal Solution? // class SimpCokeMach (continued) public static int getNumCans() { return numCans; } public static int getSerial() { return serial; } static public static int getCount() { return count; }

51 13 X 11 Inheritance

52 13 X 11 Inheritance Feature of most OO languages Based on logical organization of real world things Two main benefits –Reusability/Maintainability –Collection Processing (using polymorphism)

53 13 X 11 The Old Way Library application Book Attributes –ISBN –Title –Author –Publisher –Date –etc. What about videos, maps, CD's, etc.

54 13 X 11 Example LibraryItem BookCDMap Video Multimedia Movies

55 13 X 11 Another... VendingMachine CokeMachine FrenchFryer

56 13 X 11 class VendingMachine { private int numItems; private int maxItems; private int price; private int cash; public VendingMachine(int numItems, int maxItems, int price) { this.numItems = numItems; this.maxItems = maxItems; this.price = price; cash = 0; } public int getPrice() { return price; }

57 13 X 11 public boolean vend() { boolean retval ; if(numItems > 0) { numItems--; cash += price; retval = true; } else { retval = false; } return retval; }

58 13 X 11 public int load(int qty) { if(qty < 0) return 0; int excess = qty + numItems - maxItems; if(excess > 0) { numItems = maxItems; return qty - excess; } else { numItems += qty; return qty; }

59 13 X 11 public static void main(String args[]) { VendingMachine vm; vm = new VendingMachine(5, 60, 65); for(int i=0; i<10; i++) { if(vm.vend()) System.out.println("Vend Okay"); else System.out.println("No Vend"); } System.out.println( "Loading 40 Result: " + vm.load(40)); System.out.println( "Loading 40 Result: " + vm.load(40)); }

60 13 X 11 Test >java VendingMachine Vend Okay No Vend Loading 40 Result: 40 Loading 40 Result: 20

61 13 X 11 Sidebar on toString Every class has a toString method by default Very convenient debugging tool Sometimes used in production CokeMachine cm = new CokeMachine(); System.out.println(cm); Really : System.out.println(cm.toString()); Simply returns whatever you want to know about an object Common Errors –Must be public –Must return a String –Should never print

62 13 X 11 public String toString() { String retval; retval = "Items: " + numItems; retval += " max: " + maxItems ; retval += " price: " + price retval += " cash: " + cash; return retval; }

63 13 X 11 Adding Functionality Want a Coke Machine that gives change Over and above a Vending Machine it needs –A field for change –Modified vend method

64 13 X 11 Making a Subclass Java uses the keyword extends to express the subclass relationship class CokeMachine extends VendingMachine

65 13 X 11 class CokeMachine extends VendingMachine { private int change; public CokeMachine(int numItems, int maxItems, int price, int change) { super(numItems, maxItems, price); this.change = change; }

66 13 X 11 public boolean vend(int amount) { boolean vendResult; if(amount >= getPrice() && (amount - getPrice()) < change) { vendResult = vend(); if(vendResult) { change -= amount - getPrice(); } return vendResult; } else { return false; }

67 13 X 11 public String toString() { return "CokeMachine " + super.toString() + " change: " + change; }

68 13 X 11 public static void main(String args[]) { CokeMachine cm; cm = new CokeMachine(5, 60, 65, 100); for(int i=0; i<10; i++) { if(cm.vend(100)) { System.out.println("Vend Okay " + cm); } else { System.out.println("No Vend" + cm); } System.out.println( "Loading 40 Result: " + cm.load(40)); System.out.println( "Loading 40 Result: " + cm.load(40)); }

69 13 X 11 Output Vend Okay CokeMachine Items: 4 max: 60 price: 65 cash: 65 change: 65 Vend Okay CokeMachine Items: 3 max: 60 price: 65 cash: 130 change: 30 No VendCokeMachine Items: 3 max: 60 price: 65 cash: 130 change: 30 Loading 40 Result: 40 Loading 40 Result: 17

70 13 X 11 The French Fryer class FrenchFryer extends VendingMachine { private int oil; public static final int maxOil = 64; public static final int reqOil = 1; public FrenchFryer(int numItems, int maxItems, int price, int oil) { super( numItems, maxItems, price); if(oil > maxOil) oil = maxOil; this.oil = oil; }

71 13 X 11 public void addOil(int oil) { this.oil += oil; if(this.oil > maxOil) this.oil = maxOil; } public boolean vend() { boolean retval = false; if(oil >= reqOil) { retval = super.vend(); if(retval) { oil -= reqOil; } return retval; }

72 13 X 11 public String toString() { return "French Fryer: " + super.toString() + " oil: " + oil; }

73 13 X 11 public static void main(String args[]) { FrenchFryer ff1 = new FrenchFryer(10, 50, 50, 5); FrenchFryer ff2 = new FrenchFryer(8, 50, 50, 60); for(int i=0; i<10; i++) if(ff1.vend()) System.out.println("OK: " + ff1); else System.out.println("Fail: " + ff1); ff1.addOil(5); for(int i=0; i<10; i++) if(ff1.vend()) System.out.println("OK: " + ff1); else System.out.println("Fail: " + ff1);

74 13 X 11 for(int i=0; i<10; i++) if(ff2.vend()) System.out.println("OK: " + ff2); else System.out.println("Fail: " + ff2); }

75 13 X 11 The Test OK: French Fryer: Items: 9 max: 50 price: 50 cash: 50 oil: 4 OK: French Fryer: Items: 8 max: 50 price: 50 cash: 100 oil: 3 OK: French Fryer: Items: 7 max: 50 price: 50 cash: 150 oil: 2 OK: French Fryer: Items: 6 max: 50 price: 50 cash: 200 oil: 1 OK: French Fryer: Items: 5 max: 50 price: 50 cash: 250 oil: 0 Fail: French Fryer: Items: 5 max: 50 price: 50 cash: 250 oil: 0 OK: French Fryer: Items: 4 max: 50 price: 50 cash: 300 oil: 4 OK: French Fryer: Items: 3 max: 50 price: 50 cash: 350 oil: 3 OK: French Fryer: Items: 2 max: 50 price: 50 cash: 400 oil: 2 OK: French Fryer: Items: 1 max: 50 price: 50 cash: 450 oil: 1 OK: French Fryer: Items: 0 max: 50 price: 50 cash: 500 oil: 0

76 13 X 11 Fail: French Fryer: Items: 0 max: 50 price: 50 cash: 500 oil: 0 OK: French Fryer: Items: 7 max: 50 price: 50 cash: 50 oil: 59 OK: French Fryer: Items: 6 max: 50 price: 50 cash: 100 oil: 58 OK: French Fryer: Items: 5 max: 50 price: 50 cash: 150 oil: 57 OK: French Fryer: Items: 4 max: 50 price: 50 cash: 200 oil: 56 OK: French Fryer: Items: 3 max: 50 price: 50 cash: 250 oil: 55 OK: French Fryer: Items: 2 max: 50 price: 50 cash: 300 oil: 54 OK: French Fryer: Items: 1 max: 50 price: 50 cash: 350 oil: 53 OK: French Fryer: Items: 0 max: 50 price: 50 cash: 400 oil: 52 Fail: French Fryer: Items: 0 max: 50 price: 50 cash: 400 oil: 52

77 13 X 11 Questions?

78 13 X 11 So what's the big deal?

79 13 X 11 Advantage: Inheritance Ease of maintenance Suppose we need to add a String: name We add it to VendingMachine, recompile and we're done...

80 13 X 11 class VendingMachine { private int numItems; private int maxItems; private int price; private int cash; String name; public VendingMachine(int numItems, int maxItems, int price) { this.numItems = numItems; this.maxItems = maxItems; this.price = price; cash = 0; } public int getPrice() { return price; }

81 13 X 11 public void setName(String name) { this.name = name; } public String getName() { return name; } public String toString() { String retval; retval = getName() + ": Items: "+ numItems; retval += " max: " + maxItems ; retval += " price: " + price retval += " cash: " + cash; return retval; }

82 13 X 11 Arrays

83 13 X 11 Arrays Arrays are a little surprising (at first) in Java Arrays themselves are objects! There are two basic types of arrays –Arrays of primitives –Arrays of object references There are also multidimensional arrays which are essentially arrays of array [of arrays...] We will not go into great detail Just enough to make you dangerous Remember since an array is an object it will have a reference

84 13 X 11 Arrays of Primitives There are actually several different legal syntaxes for creating arrays. We’ll just demonstrate one. Let’s make an array of ints: int[] ia; // This is the reference ia = new int[10]; // This makes the object The array object referenced by ia can now hold 10 ints. They are numbered from 0 to 9. To learn the size of the array we can do this: ia.length Note: This is not a method call but is like an instance variable. It cannot be changed!!! for(int i=0; i < ia.length; i++) ia[i] = i * 10;

85 13 X 11 Arrays of Objects Actually, Arrays of Object References. CokeMachine[] cma; // Creates reference cma = new CokeMachine[10]; // Makes array object We now have 10 references which can refer to CokeMachine objects! They will all be initialized to null. Constructions like this are allowed CokeMachine[] cma2= {new CokeMachine(5, 60), new CokeMachine(10, 50), new CokeMachine(15, 70)};

86 13 X 11 Arrays of Object References It is very important to understand the necessity of creating new objects! CokeMachine[] cma = new CokeMachine[5]; CokeMachine cm = new CokeMachine(40,60); for(int i=0; i < cma.length; i++) { cma[i] = cm; } cma CokeMachine nC=40 mC=60 How many objects?

87 13 X 11 Arrays of Object References CokeMachine[ ] cma2 = new CokeMachine[5]; for(int i=0; i < cma2.length; i++) { cma2[i] = new CokeMachine(i*10+5, i*12+10); } cma2 How many objects? CokeMachine nC=5 mC=10 CokeMachine nC=15 mC=22 CokeMachine nC=25 mC=34 CokeMachine nC=35 mC=46 CokeMachine nC=45 mC=58

88 13 X 11 Multidimensional Arrays When you create an array using “new” and define its dimensions it will be rectangular: CokeMachine[][] a = new CokeMachine[5][7]; But it doesn’t have to be rectangular! CokeMachine[][] b = new CokeMachine[5][]; for(int i=0; i<5; i++) { b[i] = new CokeMachine[(i+1)*2]; } Don’t worry about the fine detail, just be aware that if necessary it can be done

89 13 X 11 What we got! 4 0 3 1 2 5678901234 Remember: These are CokeMachine references...not CokeMachines Don't panic...we won't ask you to do anything like this...at least not in CS 1311X

90 13 X 11 Questions?

91


Download ppt "Java Lecture 4 CS 1311X Have a Coke! 13 X 11. Take the Survey!"

Similar presentations


Ads by Google