Upload
blanca-dorrell
View
214
Download
0
Tags:
Embed Size (px)
Citation preview
Java Lecture 4
CS 1311X
Have a Coke!
13X11
13X11
Take the Survey!
http://www.coursesurvey.gatech.edu
Today's Lecture brought to you with the kind assistance of...
13X11
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
13X11
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.");
}
}
13X11
The story so far...// class CokeMachine (continued)
public void load(int n) {
numCans += n;
System.out.println("Loaded with " + numCans);
}
}
13X11
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?)
13X11
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
13X11
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
13X11
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;
}
}
13X11
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
13X11
Testing Using a test Main// Static method for testing coke machines
public static void vendNCokes(int n, CokeMachine cm){
for(int i=0; i<n; i++) {
if(cm.vend()) {
System.out.print("Coke! ");
} else {
System.out.println("Empty");
}
}
} // vendNCokes
13X11
Testing Using a test Mainpublic 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
13X11
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
>
13X11
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
13X11
Adding a Constructorclass 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);
13X11
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()
13X11
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:
13X11
The Mysterious Default Constructor
• Well actually it's invisible but if you could see it then it would look like this:
public CokeMachine()
{
}
13X11
So where did it go?
• Java giveth...• Java taketh away...
• As soon as you define any constructor the default constructor no longer exists.
• Why?
13X11
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;
}
13X11
You could even do thisclass 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 */
}
13X11
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.
Methods which modify the value of variables inside of the object or class are known as modifiers.
13X11
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.
Methods which return the value of variables inside of the object or class are known as accessors.
13X11
Notice the parameter namesclass CokeMachine {
private int numCans;
private int maxCans;
// Constructor
public CokeMachine(int num, int max) {
numCans = num;
maxCans = max;
}
13X11
We want...
• To name the parametersnumCans
maxCans
• Why?
• Two reasons– Documentation– Nature of CS Guys
13X11
Documentation
13X11
Typical CS Geeks Guys
13X11
Typical CS Geeks GuysHeh, heh...
My high score in Space Invaders
was 257,368
13X11
Typical CS Geeks Guys
I wonder if Java Beans
will give me gas?
13X11
Typical CS Geeks Guys
I wonder howmuch of a curve
there will bein CS 1311X?
13X11
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;
}
13X11
Writing like the big kids...class CokeMachine {
private int numCans;
private int maxCans;
// Constructor
public CokeMachineCokeMachine(int numCans, int maxCans) {
this.numCans = numCans;
this.maxCans = maxCans;
}
public CokeMachine() {
thisthis(3, 60);
}Constructor Chaining
13X11
How do it know?
• Java differentiates constructors using the parameter list
• CokeMachine()• CokeMachine(int, int)
• Note: Same idea works for methods
13X11
Lots of flexibilityclass CokeMachine {
private int numCans;
private int maxCans;
private String name;
public CokeMachineCokeMachine(String name,
int numCans,
int maxCans) {
this.numCans = numCans;
this.maxCans = maxCans;
this.name = name;
}
13X11
Lots of flexibility// class CokeMachine (continued)
public CokeMachineCokeMachine(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);
}
13X11
Let's not get carried away!// class CokeMachine (continued)
public CokeMachineCokeMachine(int numCans) {
this("unnamed", numCans, 60);
}
public CokeMachine(int maxCans) {
this("unnamed", 3, maxCans);
}
13X11
Lots of flexibility// class CokeMachine (continued)
public CokeMachineCokeMachine(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);
}
13X11
Why so many constructors?
• User convenience
• CS 1312
13X11
Recall Kurt's Dream
class CokeMachine {private int numCans;private int maxCans;private String name;
...}
CokeMachine ObjectnumCans = ___maxCans = ___name = ___
CokeMachine ObjectnumCans = ___maxCans = ___name = ___
CokeMachine ObjectnumCans = ___maxCans = ___name = ___
CokeMachine ObjectnumCans = ___maxCans = ___name = ___
13X11
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???
13X11
Adding a Serial Numberclass CokeMachine {
private int numCans;private int maxCans;private String name;private int serial;private static int count = 0;
public CokeMachineCokeMachine(String name, int numCans, int maxCans) {
this.numCans = numCans;this.maxCans = maxCans;this.name = name;count++;serial = count;
}
Note: Since we usedconstructor chainingall the other constructorsstill work!
13X11
Recall Kurt's Dream
class CokeMachine {private int numCans;private int maxCans;private String name;private int serial;private static int count = 3;
...}
CokeMachine ObjectnumCans = 3maxCans = 60name = "CoC"serial = 1static count
CokeMachine ObjectnumCans = 3maxCans = 60name = "CoC"serial = 3static count
CokeMachine ObjectnumCans = 3maxCans = 60name = "CoC"serial = 2static count
13X11
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
13X11
Examplesclass SimpCokeMach {
int numCans
int serial;
static int count = 0;
public SimpCokeMach() {
numCans = 10;
count++;
serial = count;
}
13X11
Examples// class SimpCokeMach (continued)
public int getNumCans() {
return numCans;
}
public int getSerial() {
return serial;
}
public int getCount() {
return count;
}
13X11
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());
}
13X11
Examples// class SimpCokeMach (continued)
public int getNumCans() {
return numCans;
}
public int getSerial() {
return serial;
}
public static int getCount() {
return count;
}
13X11
Examplesclass 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());
}
}
13X11
Universal Solution?// class SimpCokeMach (continued)
public static int getNumCans() {
return numCans;
}
public static int getSerial() {
return serial;
}
public staticstatic int getCount() {
return count;
}
13X11
Inheritance
13X11
Inheritance
• Feature of most OO languages• Based on logical organization of real world things
• Two main benefits– Reusability/Maintainability– Collection Processing (using polymorphism)
13X11
The Old Way
• Library application• Book Attributes
– ISBN– Title– Author– Publisher– Date– etc.
• What about videos, maps, CD's, etc.
13X11
Example
LibraryItem
Book CDMap
Video
Multimedia
Movies
13X11
Another...
VendingMachine
CokeMachine FrenchFryer
13X11
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;
}
13X11
public boolean vend()
{
boolean retval ;
if(numItems > 0)
{
numItems--;
cash += price;
retval = true;
}
else
{
retval = false;
}
return retval;
}
13X11
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;
}
}
13X11
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));
}
}
13X11
Test>java VendingMachine
Vend Okay
Vend Okay
Vend Okay
Vend Okay
Vend Okay
No Vend
No Vend
No Vend
No Vend
No Vend
Loading 40 Result: 40
Loading 40 Result: 20
13X11
Sidebaron
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
13X11
public String toString()
{
String retval;
retval = "Items: " + numItems;
retval += " max: " + maxItems ;
retval += " price: " + price
retval += " cash: " + cash;
return retval;
}
13X11
Adding Functionality
• Want a Coke Machine that gives change• Over and above a Vending Machine it needs
– A field for change– Modified vend method
13X11
Making a Subclass
• Java uses the keyword extends to express the subclass relationship
class CokeMachine extends VendingMachine
13X11
class CokeMachine extends VendingMachine {
private int change;
public CokeMachine(int numItems, int maxItems,
int price, int change) {
super(numItems, maxItems, price);
this.change = change;
}
13X11
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;
}
}
13X11
public String toString()
{
return "CokeMachine "
+ super.toString()
+ " change: "
+ change;
}
13X11
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));
}
}
13X11
OutputVend 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
No VendCokeMachine Items: 3 max: 60 price: 65 cash: 130 change: 30
No VendCokeMachine Items: 3 max: 60 price: 65 cash: 130 change: 30
No VendCokeMachine Items: 3 max: 60 price: 65 cash: 130 change: 30
No VendCokeMachine Items: 3 max: 60 price: 65 cash: 130 change: 30
No VendCokeMachine Items: 3 max: 60 price: 65 cash: 130 change: 30
No VendCokeMachine 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
13X11
The French Fryerclass 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;
}
13X11
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;
}
13X11
public String toString()
{
return "French Fryer: " + super.toString() + " oil: " + oil;
}
13X11
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);
13X11
for(int i=0; i<10; i++)
if(ff2.vend())
System.out.println("OK: " + ff2);
else
System.out.println("Fail: " + ff2);
}
}
13X11
The TestOK: 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
Fail: 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
Fail: 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
13X11
Fail: French Fryer: Items: 0 max: 50 price: 50 cash: 500 oil: 0
Fail: French Fryer: Items: 0 max: 50 price: 50 cash: 500 oil: 0
Fail: French Fryer: Items: 0 max: 50 price: 50 cash: 500 oil: 0
Fail: French Fryer: Items: 0 max: 50 price: 50 cash: 500 oil: 0
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
Fail: French Fryer: Items: 0 max: 50 price: 50 cash: 400 oil: 52
13X11
Questions?
13X11
So what's the big deal?
13X11
Advantage: Inheritance
• Ease of maintenance
• Suppose we need to add a String: name
• We add it to VendingMachine, recompile and we're done...
13X11
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;
}
13X11
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;
}
13X11
Arrays
13X11
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
13X11
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;
13X11
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)};
13X11
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?How many objects?
13X11
Arrays of Object ReferencesCokeMachine[ ] 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?How many objects?
CokeMachinenC=5 mC=10
CokeMachinenC=15 mC=22
CokeMachinenC=25 mC=34
CokeMachinenC=35 mC=46
CokeMachinenC=45 mC=58
13X11
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
13X11
What we got!
4
0
3
1
2
5 6 7 8 90 1 2 3 4
Remember: These are CokeMachinereferences...not CokeMachines
Don't panic...we won't ask you to do anything like this...at least not in CS 1311X
13X11
Questions?