420 likes | 525 Views
Learning java in 180 minutes. With Kasper B. Graversen. Todays program. Understanding classesattributes methods constructors access modifiers final, static Understanding scopes and references Classes using other classes Stockmarket Linked lists. The linked list.
E N D
Learning java in 180 minutes . . With Kasper B. Graversen
Todays program • Understanding classesattributes • methods • constructors • access modifiers • final, static • Understanding scopes and references • Classes using other classes • Stockmarket • Linked lists (c) Kasper B. Graversen
The 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
Chapter 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
Chapter 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
Drawing 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
User String name double balance LinkedList stocks buyStocks() sellStocks() Stock String name double val int amount Drawing UML * 1 Static: Stock Dynamic: Stock User 400 LinkedList Stock “Sam” Stock (c) Kasper B. Graversen
Class 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
Class building • Decide the valid data needed to create objects. • Constructors must be build utilizing this data class 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
Class 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
Class 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
Class 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
Study 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
Study Case: Stock trading • The screen seen from the user (c) Kasper B. Graversen
Object 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
Object 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" account -ing main program internet connect load/ save (c) Kasper B. Graversen
Study 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
Study Case: Stock trading • A stock trading central is a place where stocks can be bought and soldby 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
Study 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
Study Case: Stock trading • A stock trading central is a place where stocks can be bought and sold by users. • Users can hold several differentstocks 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
Study Case: Stock trading • Static UML 1 * Stock User * 1 * 1 StockCentral 1 1 GUI (c) Kasper B. Graversen
Stock String name double val int amount Study Case: Stock trading User +String name -double balance -LinkedList stocks +buyStocks(Stock stock) +sellStocks(int StockNo) +printInfo() 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) + denotes public - denotes private Due to lack of space types are not shown (c) Kasper B. Graversen GUI
Stock trading: StockGUI import 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
Stock 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
Stock String name double val int amount Study Case: Stock trading User +String name -double balance -LinkedList stocks +buyStocks(Stock stock) +sellStocks(int StockNo) +printInfo() 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) + denotes public - denotes private Due to lack of space types are not shown (c) Kasper B. Graversen GUI
Stock trading: Stock • The Stock is a simple "container class" as there is no functionality. • What does it represent? an amount of stocks class 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
Stock 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
Stock String name double val int amount Study Case: Stock trading User +String name -double balance -LinkedList stocks +buyStocks(Stock stock) +sellStocks(int StockNo) +printInfo() 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) + denotes public - denotes private Due to lack of space types are not shown (c) Kasper B. Graversen GUI
class 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); } } Stock trading: User (c) Kasper B. Graversen
(((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); } } Stock trading: User How to expand it so it will print the total wealth the user has? (c) Kasper B. Graversen
Stock trading: User At each iteration we accumulate the value for the set of stocks 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); } If stocks change then this number only shows the money spent! (c) Kasper B. Graversen
Repetition: 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
Stock String name double val int amount Study Case: Stock trading User +String name -double balance -LinkedList stocks +buyStocks(Stock stock) +sellStocks(int StockNo) +printInfo() 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) + denotes public - denotes private Due to lack of space types are not shown (c) Kasper B. Graversen GUI
Stock trading: StockCentral 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
Stock trading: StockCentral (((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
Stock trading: StockCentral (((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"); } (c) Kasper B. Graversen
Stock trading: StockCentral • 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
Stock trading: StockCentral (((continued))) public void turn() { stockChange(); display.fetchValues(); } // change the value of all stocks private 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
Stock trading: StockCentral (((continued))) public static void main(String[]args) { StockCentral central = new StockCentral(); for(int i = 0; i < 365; i++) central.round(); } } (c) Kasper B. Graversen
Scopes Test 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); } } • What does the following program output? (c) Kasper B. Graversen
head s Linked Lists • Each object has a pointer to the next object SOS B&T T&A BBQ 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); (c) Kasper B. Graversen
The end... • Happy holidays • The rest of the course will be lectured by Uffe Kofoed • bye bye & merry X-mas :-) (c) Kasper B. Graversen