Learning java in 180 minutes With Kasper B. Graversen

Preview:

Citation preview

Learning java in 180 Learning java in 180 minutesminutes

With Kasper B. GraversenWith Kasper B. Graversen ....

(c) Kasper B. Graversen 2

Todays programTodays program

• Understanding classesattributes– methods– constructors– access modifiers– final, static

• Understanding scopes and references

• Classes using other classes– Stockmarket – Linked lists

(c) Kasper B. Graversen 3

The linked listThe linked list

• The linked list works as Vector • It differs in that it is never and the

underlaying structure is a linked list rather than a big array

• The methods are still the same• get(),set(),size(),remove()• LinkedList

(c) Kasper B. Graversen 4

Chapter 8Chapter 8

• Don't panic over chapter 8• It shortly tells about advanced features in

java such as classes inside classes.• However, you should relate and understand

the clone() and iterator()• The coffee example is a bit long but worth

reading when you• However, mind that linked list can get fairly

advanced should you think of functionality not covered in the book. So read it and try best possible to understand it

(c) Kasper B. Graversen 5

Chapter 8Chapter 8

• Iterators may to you seem like a strange construction when you have for-loops and while-loops.

• At this stage just understand it as an alternative to the looping mechanisms in java.

• In later programming courses you will see that the idea "iterator" is very usefull for different traversals of a set of data.

(c) Kasper B. Graversen 6

Drawing UMLDrawing UML

• Two kinds of UML– Dynamic

• Runtime - hence dynamic• Showing a situation at a certain point of the

program execution (typically after basic initialization)

– Static• Compiletime - hence static• Shows the overall relations between classes

which can be read directly from the source code

(c) Kasper B. Graversen 7

Drawing UMLDrawing UML

Static:

Dynamic:

*1 StockString namedouble valint amount

LinkedList

Stock

Stock

Stock

Stock“Sam”

User400

UserString namedouble balanceLinkedList stocksbuyStocks()sellStocks()

(c) Kasper B. Graversen 8

Class buildingClass building• Define the appropiate attributes

– Proper names, not (a,b,c)– Choose the proper types

• Simple types int,long,float,double, boolean,char

• Pointers to objects

– May consider differentiating between attributes for the object and for “accounting”• for a customer object the name and the total

amount of money spent

• Attributes define the states in which object can be in

(c) Kasper B. Graversen 9

Class buildingClass building

• Decide the valid data needed to create objects.

• Constructors must be build utilizing this dataclass User{ String name; double balance; User(String name, double balance) { this.balance=balance; this.name = name; } … User u = new User("Kasper", 10000.0);

same order

(c) Kasper B. Graversen 10

Class buildingClass building• If you have more than one constructor

we say the constructor is overloaded.• Each constructor must have a

different signature from the others• A signature is the number of

arguments and their types

User(String name){…}User(String name, double balance) {…}User(String foo, String bar){…}

User u1 = new User("Bent", 3.4);User u2 = new User("Bent","Sam");User u3 = new User("Bent");

(c) Kasper B. Graversen 11

Class buildingClass building• At this stage we now need to define

the functionality of the object. • However, not all objects have

functionality - ie. the Stock object• For each functionality we create a

method.• If methods can be overloaded

aswell as constructors - as long as the overloaded methods has different signatures (you can't overload the return value)

(c) Kasper B. Graversen 12

Class buildingClass building• After building a class we apply access

modifiers to protect the object.• The more restricted the object is the

easier it is to use/re-use• And the more secure we are that nothing

completely weird happens• We apply public in front of all attributes,

constructors and methods which may be accessed by others

• And we apply private in front of those which are only for internal purposes.

(c) Kasper B. Graversen 13

Study Case: Stock tradingStudy Case: Stock trading

• A stock trading central is a place where stocks can be bought and sold by users.

• Users can hold several different stocks including stocks from the same compagny but with different values.

• User interact with the trading central through a GUI.

(c) Kasper B. Graversen 14

Study Case: Stock tradingStudy Case: Stock trading

• The screen seen from the user

(c) Kasper B. Graversen 15

Object Oriented DesignObject Oriented Design

• How do we create this program in Java?

• We identify building blocks (objects) which together makes the system

• We identify the needed functionality and attributes needed in these building blocks

(c) Kasper B. Graversen 16

Object Oriented DesignObject Oriented Design

• We try to isolate functionality so that only one object is responsible for a certain task

• This object may use other objects to further split the task, however, it should be the only one accessing these "helper objects"

internetconnect

mainprogram

load/save

account-ing

(c) Kasper B. Graversen 17

Study Case: Stock tradingStudy Case: Stock trading

• A stock trading central is a place where stocks can be bought and sold by users.

• Users can hold several different stocks including stocks from the same compagny but with different values.

• User interact with the trading central through a GUI.

(c) Kasper B. Graversen 18

Study Case: Stock tradingStudy Case: Stock trading

• A stock trading central is a place where stocks can be bought and sold by users.

• Users can hold several different stocks including stocks from the same compagny but with different values.

• User interact with the trading central through a GUI.

classes = green

(c) Kasper B. Graversen 19

Study Case: Stock tradingStudy Case: Stock trading

• A stock trading central is a place where stocks can be bought and sold by users.

• Users can hold several different stocks including stocks from the same compagny but with different values.

• User interact with the trading central through a GUI.

classes = green functionality = purple

(c) Kasper B. Graversen 20

Study Case: Stock tradingStudy Case: Stock trading

• A stock trading central is a place where stocks can be bought and sold by users.

• Users can hold several different stocks including stocks from the same compagny but with different values.

• User interact with the trading central through a GUI.

classes = green functionality = purple attributes = yellow

(c) Kasper B. Graversen 21

Study Case: Stock tradingStudy Case: Stock trading

• Static UML

StockCentral

GUI

StockUser

1

1

1*1

*

1*

(c) Kasper B. Graversen 22

User+String name-double balance-LinkedList stocks+buyStocks(Stock stock) +sellStocks(int StockNo)+printInfo()

Study Case: Stock tradingStudy Case: Stock trading

StockCentral-Display display-LinkedList users-LinkedList stocks+buyStocks(usr,stock,amoun)+sellStocks(usr,stock,amount)+User userInfo()+addUser(String,int) +turn()-stockChange()-findUser(String name)-findStock(String name)

GUI

StockString namedouble valint amount

+ denotes public- denotes privateDue to lack of space types are not shown

(c) Kasper B. Graversen 23

Stock trading: StockGUIStock trading: StockGUIimport javagently.Display;

class StockGUI{ StockCentral central; Display display = new Display("Stock central");

StockGUI(StockCentral central) { this.central = central; display.prompt("name", " "); display.prompt("what", "buy/sell"); display.prompt("no", "number"); display.println("Welcome to the stock central"); display.ready(); }

(c) Kasper B. Graversen 24

Stock trading: StockGUIStock trading: StockGUI((continued))

public void fetchValues() { …"fetch the values"… if(display.getString("what").equals("buy")) central.buyStocks(…); if(display.getString("what").equals("sell")) central.sellStocks(…); }

public void println(String s) { display.println(s); }}

(c) Kasper B. Graversen 25

User+String name-double balance-LinkedList stocks+buyStocks(Stock stock) +sellStocks(int StockNo)+printInfo()

Study Case: Stock tradingStudy Case: Stock trading

StockCentral-Display display-LinkedList users-LinkedList stocks+buyStocks(usr,stock,amoun)+sellStocks(usr,stock,amount)+User userInfo()+addUser(String,int) +turn()-stockChange()-findUser(String name)-findStock(String name)

GUI

StockString namedouble valint amount

+ denotes public- denotes privateDue to lack of space types are not shown

(c) Kasper B. Graversen 26

Stock trading: StockStock trading: Stock• The Stock is a simple "container class" as

there is no functionality.• What does it represent? an amount of

stocksclass Stock{ public String name; public double val; public int amount;

public Stock(String name, double val, int amount) { this.name = name; this.val = val; this.amount = amount; }}

"this" refers to the variables in the class scope

(c) Kasper B. Graversen 27

Stock trading: UserStock trading: User• Users is roughly a collection of stocks

identified by a name• Notice that the StockCentral is the

central class in the system (like an octapussy holding on to all essential parts). It has full control. The user has no way of cheating.

(c) Kasper B. Graversen 28

User+String name-double balance-LinkedList stocks+buyStocks(Stock stock) +sellStocks(int StockNo)+printInfo()

Study Case: Stock tradingStudy Case: Stock trading

StockCentral-Display display-LinkedList users-LinkedList stocks+buyStocks(usr,stock,amoun)+sellStocks(usr,stock,amount)+User userInfo()+addUser(String,int) +turn()-stockChange()-findUser(String name)-findStock(String name)

GUI

StockString namedouble valint amount

+ denotes public- denotes privateDue to lack of space types are not shown

(c) Kasper B. Graversen 29

Stock trading: UserStock trading: Userclass User{ public String name; private double balance; private LinkedList stocks;

public User(String name, double balance) { this.name = name; this.balance = balance; stocks = new LinkedList(); }

public buyStocks(Stock stock) { stocks.add(stock); balance -= stock.amount * val; }

public sellStocks(int stockNo, int amount) { Stock stock = (Stock) stocks.get(stockNo); if(amount <= stock.amount) { balance += amoung * stock.val; stock.amount -= amount; if(stock.amount == 0) stocks.remove(stockNo); } }

(c) Kasper B. Graversen 30

Stock trading: UserStock trading: User (((class User continued))) public void printInfo(Display display) { display.println(name + " you have the following stocks"); for(int i = 0; i < stocks.size(); i++) { Stock stock = (Stock) stocks.get(i); display.println("#" +i+ " " +stock.name+ " " +stock.amount+ " at $" +stock.val); } display.println("And a balance of " + balance); }}

How to expand it so it will print the total wealth the user has?

(c) Kasper B. Graversen 31

Stock trading: UserStock trading: User

public void printInfo(Display display){ double totalwealth = 0; display.println(name + " you have the following stocks"); for(int i = 0; i < stocks.size(); i++) { Stock stock = (Stock) stocks.get(i); display.println("#" +i+ " " +stock.name+ " " +stock.amount+ " at $" +stock.val); totalwealth += stock.amount * stock.val; } display.println("And a balance of " + balance); display.println("total balance " + totalwealth);}

At each iteration we accumulate the value for the set of stocks

If stocks change then this number only shows the money spent!

(c) Kasper B. Graversen 32

Repetition: VariablesRepetition: Variables• What does the statement b mean? ie. in a = b + c– It means "read the value of the variable b" (if

the variable is a simeple type)

– Or tell which object b is pointing at(if the variable is not a simeple type)

• The order of evaluation– Evaluate the rigth side and set the value to the left side,

ie. a = b + a(read the value of b and a and add them, and assign the variable a to the result

(c) Kasper B. Graversen 33

User+String name-double balance-LinkedList stocks+buyStocks(Stock stock) +sellStocks(int StockNo)+printInfo()

Study Case: Stock tradingStudy Case: Stock trading

StockCentral-Display display-LinkedList users-LinkedList stocks+buyStocks(usr,stock,amoun)+sellStocks(usr,stock,amount)+User userInfo()+addUser(String,int) +turn()-stockChange()-findUser(String name)-findStock(String name)

GUI

StockString namedouble valint amount

+ denotes public- denotes privateDue to lack of space types are not shown

(c) Kasper B. Graversen 34

Stock trading: Stock trading: StockCentralStockCentral

import javagently.*;class StockCentral{ StockGUI display; LinkedList users; LinkedList stocks;

StockCentral() { display = new StockGUI(this); users = new LinkedList(); stocks = new LinkedList(); users.add(new User("Hansi", 1000.0)); users.add(new User("Liza", 2000.0)); stocks.add(new Stock("IBM", 1000, 2000)); stocks.add(new Stock("RedHat", 1000, 888)); stocks.add(new Stock("Jedit", 10, 40)); }

(c) Kasper B. Graversen 35

Stock trading: Stock trading: StockCentralStockCentral(((continued)))

public void buyStocks(String usrnam, String stocknam, int amt){try { User user = findUser(usrnam); //get at reference to the user Stock stock = findStock(stocknam,amt); // get new stock object user.buyStocks(stock); } catch(Exception e){ display.println(e.getMessage()); }}

private User findUser(String name){ User user = null; for(int i = 0; i < users.size(); i++)//search the list of users { user = (User) users.get(i); // get the i'th user if(user.name.equals(name)) return user; // if it's the user return } throw new Exception("User not found");}

(c) Kasper B. Graversen 36

(((continued)))

private Stock findStock(String stockname, int amount){ Stock stock = null; for(int i = 0; i < stocks.size(); i++)//search the stocks { stock = stocks.get(i); // get the i'th stock if(stock.name.equals(stockname)) { if(stock.amount >= amount) { stock.amount -= amount; stock = new Stock(stock.name, amount); return stock; } throw new Exception("Not enough stocks"); } } throw new Exception("The stock was not found");}

Stock trading: Stock trading: StockCentralStockCentral

(c) Kasper B. Graversen 37

Stock trading: Stock trading: StockCentralStockCentral

• Why do we create a new Stock and not a new User?

• The amount the User has and the amoun which are at the StockCentral are different

• The User and the StockCentral should not share the same stocks, as the Stock's in StockCentral changes value all the time

(c) Kasper B. Graversen 38

Stock trading: Stock trading: StockCentralStockCentral

(((continued)))

public void turn(){ stockChange(); display.fetchValues();}

// change the value of all stocksprivate void stockChange() { Stock stock; for(int i = 0; i < stocks.size(); i++) { stock = stocks.get(i); stock.val += (Math.random()-0.5)*stock.val; }}

(c) Kasper B. Graversen 39

Stock trading: Stock trading: StockCentralStockCentral

(((continued)))

public static void main(String[]args) { StockCentral central = new StockCentral(); for(int i = 0; i < 365; i++) central.round(); }}

(c) Kasper B. Graversen 40

Scopes TestScopes Test

• What does the following program output?class Foo{ int x, y; void bar(int x, int y) { this.x = x; this.y = y; x = calc(); y = calc(); } int calc(){return -100;}

public static void main(String[] args) { Foo bar = new Foo(); bar.bar(1,2); System.out.println(bar.x +" " + bar.y); }}

(c) Kasper B. Graversen 41

• Each object has a pointer to the next object

Linked ListsLinked Lists

class Stock{ String name; double val; Stock next; Stock(String n,double v, Stock ne) { name=n;val=v; next = ne; } }

Stock s = new Stock("SOS",55, null);s = new Stock("BBQ", 222, s);s = new Stock("T&A", 8, s);Stock head = new Stock("B&T",123, s);

SOSBBQT&AB&T

head s

(c) Kasper B. Graversen 42

The end...The end...

• Happy holidays• The rest of the course will be lectured

by Uffe Kofoed – bye bye & merry X-mas :-)