java lecture 4 l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Java Lecture 4 PowerPoint Presentation
Download Presentation
Java Lecture 4

Loading in 2 Seconds...

play fullscreen
1 / 91

Java Lecture 4 - PowerPoint PPT Presentation


  • 137 Views
  • Uploaded on

Java Lecture 4. CS 1311X Have a Coke!. 13 X 11. Take the Survey!. http://www.coursesurvey.gatech.edu. Today's Lecture brought to you with the kind assistance of. Juicing Up the Coke Machine. Adding cash More methods Adding setup flexibility Constructors Adding a serial number

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Java Lecture 4' - gaston


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
java lecture 4

Java Lecture 4

CS 1311X

Have a Coke!

13X11

take the survey

Take the Survey!

http://www.coursesurvey.gatech.edu

juicing up the coke machine
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
the story so far
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.");

}

}

the story so far6
The story so far...

// class CokeMachine (continued)

public void load(int n) {

numCans += n;

System.out.println("Loaded with " + numCans);

}

}

issues
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?)
how many cans can the machine hold
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

how many cans can the machine hold9
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

should the machine print things out
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;

}

}

should the machine print things out11
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

testing using a test main
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

testing using a test main13
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

result
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

>

vary initial number of cans
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
adding a constructor
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);

what happened
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()

the mysterious default constructor
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:
the mysterious default constructor19
The Mysterious Default Constructor
  • Well actually it's invisible but if you could see it then it would look like this:

public CokeMachine()

{

}

so where did it go
So where did it go?
  • Java giveth...
  • Java taketh away...
  • As soon as you define any constructor the default constructor no longer exists.
  • Why?
but i want one
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;

}

you could even do this
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 */

}

so you would need these
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.

you could also write these
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.

notice the parameter names
Notice the parameter names

class CokeMachine {

private int numCans;

private int maxCans;

// Constructor

public CokeMachine(int num, int max) {

numCans = num;

maxCans = max;

}

we want
We want...
  • To name the parameters

numCans

maxCans

  • Why?
  • Two reasons
    • Documentation
    • Nature of CS Guys
typical cs geeks guys29
Typical CS Geeks Guys

Heh, heh...

My high score in

Space Invaders

was 257,368

typical cs geeks guys30
Typical CS Geeks Guys

I wonder if

Java Beans

will give me gas?

typical cs geeks guys31
Typical CS Geeks Guys

I wonder how

much of a curve

there will be

in CS 1311X?

writing like the big kids
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;

}

writing like the big kids33
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() {

this(3, 60);

}

Constructor Chaining

how do it know
How do it know?
  • Java differentiates constructors using the parameter list
  • CokeMachine()
  • CokeMachine(int, int)
  • Note: Same idea works for methods
lots of flexibility
Lots of flexibility

class CokeMachine {

private int numCans;

private int maxCans;

private String name;

public CokeMachine(String name,

int numCans,

int maxCans) {

this.numCans = numCans;

this.maxCans = maxCans;

this.name = name;

}

lots of flexibility36
Lots of flexibility

// class CokeMachine (continued)

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);

}

let s not get carried away
Let's not get carried away!

// class CokeMachine (continued)

public CokeMachine(int numCans) {

this("unnamed", numCans, 60);

}

public CokeMachine(int maxCans) {

this("unnamed", 3, maxCans);

}

lots of flexibility38
Lots of flexibility

// class CokeMachine (continued)

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);

}

why so many constructors
Why so many constructors?
  • User convenience
  • CS 1312
recall kurt s dream
Recall Kurt's Dream

CokeMachine Object

numCans = ___

maxCans = ___

name = ___

CokeMachine Object

numCans = ___

maxCans = ___

name = ___

CokeMachine Object

numCans = ___

maxCans = ___

name = ___

class CokeMachine {

private int numCans;

private int maxCans;

private String name;

...

}

CokeMachine Object

numCans = ___

maxCans = ___

name = ___

want to have a serial number
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???
adding a serial number
Adding a Serial Number

class CokeMachine {

private int numCans;

private int maxCans;

private String name;

private int serial;

private static int count = 0;

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!

recall kurt s dream43
Recall Kurt's Dream

CokeMachine Object

numCans = 3

maxCans = 60

name = "CoC"

serial = 2

static count

CokeMachine Object

numCans = 3

maxCans = 60

name = "CoC"

serial = 3

static count

CokeMachine Object

numCans = 3

maxCans = 60

name = "CoC"

serial = 1

static count

class CokeMachine {

private int numCans;

private int maxCans;

private String name;

private int serial;

private static int count = 3;

...

}

static vs instance
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
examples
Examples

class SimpCokeMach {

int numCans

int serial;

static int count = 0;

public SimpCokeMach() {

numCans = 10;

count++;

serial = count;

}

examples46
Examples

// class SimpCokeMach (continued)

public int getNumCans() {

return numCans;

}

public int getSerial() {

return serial;

}

public int getCount() {

return count;

}

examples47
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());

}

examples48
Examples

// class SimpCokeMach (continued)

public int getNumCans() {

return numCans;

}

public int getSerial() {

return serial;

}

public static int getCount() {

return count;

}

examples49
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());

}

}

universal solution
Universal Solution?

// class SimpCokeMach (continued)

public static int getNumCans() {

return numCans;

}

public static int getSerial() {

return serial;

}

public static int getCount() {

return count;

}

inheritance52
Inheritance
  • Feature of most OO languages
  • Based on logical organization of real world things
  • Two main benefits
    • Reusability/Maintainability
    • Collection Processing (using polymorphism)
the old way
The Old Way
  • Library application
  • Book Attributes
    • ISBN
    • Title
    • Author
    • Publisher
    • Date
    • etc.
  • What about videos, maps, CD's, etc.
example
Example

LibraryItem

Book

Map

CD

Multimedia

Video

Movies

another
Another...

VendingMachine

CokeMachine

FrenchFryer

slide56
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;

}

slide57
public boolean vend()

{

boolean retval ;

if(numItems > 0)

{

numItems--;

cash += price;

retval = true;

}

else

{

retval = false;

}

return retval;

}

slide58
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;

}

}

slide59
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));

}

}

slide60
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

sidebar on tostring
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
slide62
public String toString()

{

String retval;

retval = "Items: " + numItems;

retval += " max: " + maxItems ;

retval += " price: " + price

retval += " cash: " + cash;

return retval;

}

adding functionality
Adding Functionality
  • Want a Coke Machine that gives change
  • Over and above a Vending Machine it needs
    • A field for change
    • Modified vend method
making a subclass
Making a Subclass
  • Java uses the keyword extends to express the subclass relationship

class CokeMachine extends VendingMachine

slide65
class CokeMachine extends VendingMachine {

private int change;

public CokeMachine(int numItems, int maxItems,

int price, int change) {

super(numItems, maxItems, price);

this.change = change;

}

slide66
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;

}

}

slide67
public String toString()

{

return "CokeMachine "

+ super.toString()

+ " change: "

+ change;

}

slide68
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));

}

}

output
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

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

the french fryer
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;

}

slide71
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;

}

slide72
public String toString()

{

return "French Fryer: " + super.toString() + " oil: " + oil;

}

slide73
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);

slide74
for(int i=0; i<10; i++)

if(ff2.vend())

System.out.println("OK: " + ff2);

else

System.out.println("Fail: " + ff2);

}

}

the test
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

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

slide76
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

advantage inheritance
Advantage: Inheritance
  • Ease of maintenance
  • Suppose we need to add a String: name
  • We add it to VendingMachine, recompile and we're done...
slide80
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;

}

slide81
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;

}

arrays83
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
arrays of primitives
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;

arrays of objects
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)};

arrays of object references
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

How many objects?

CokeMachine nC=40 mC=60

arrays of object references87
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

CokeMachine

nC=5 mC=10

CokeMachine

nC=45 mC=58

CokeMachine

nC=15 mC=22

CokeMachine

nC=35 mC=46

CokeMachine

nC=25 mC=34

How many objects?

multidimensional arrays
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
what we got
What we got!

Remember: These are CokeMachine

references...not CokeMachines

0

1

2

3

4

0

1

2

3

4

5

6

7

8

9

Don't panic...we won't ask you to do anything like this...at least not in CS 1311X