Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science A 8: 6/3. Group data in an object class PlayerData{ String name; int score; }.. PlayerData d=new PlayerData(); d.name=“Mads”; d.score=100;

Similar presentations


Presentation on theme: "Computer Science A 8: 6/3. Group data in an object class PlayerData{ String name; int score; }.. PlayerData d=new PlayerData(); d.name=“Mads”; d.score=100;"— Presentation transcript:

1 Computer Science A 8: 6/3

2 Group data in an object class PlayerData{ String name; int score; }.. PlayerData d=new PlayerData(); d.name=“Mads”; d.score=100;

3 Use objects PlayerData d=new PlayerData(); d.name=“Mads”; d.score=100; PlayerData d2=null; d2=d; //copy reference to object d=null; System.out.println(d2.name); // it’s Mads

4 Classes class PlayerData{ static int cnt=0; // static field static void incc(){cnt++;} // static method String name; // instance variable String getName(){return name;} // instance method PlayerData(String nm){name=nm;} // constructor } static: one per class, instance: one per object Static fields and methods can be used in instance methods

5 Public /private Class PlayerData{ private String name; private int score; PlayerData(String nm){ name = nm; score = 0; } public String getName(){return name;} public void addScore(int n){score+=n; } } You cannot acces name and score from outside the class

6 Getter – setter methods public String getName(){return name;} public void setName(String nm){name=nm;} You can check values before they are assigned to fields Wrapper methods – Objects that can contain simple values Autoboxing autounboxing Integer ii = 3; int i= ii; ii = new Integer(7);

7 Designing Classes A class represents a single concept from the problem domain Name for a class should be a noun that describes concept Concepts from mathematics: Point Rectangle Ellipse Concepts from real life BankAccount CashRegister

8 Choosing Classes Actors (end in -er, -or)–objects do some kinds of work for you Scanner Random // better name: RandomNumberGenerator Utility classes–no objects, only static methods and constants Math Program starters: only have a main method Don't turn actions into classes: Paycheck is better name than ComputePaycheck

9 Cohesion A class should represent a single concept The public interface of a class is cohesive if all of its features are related to the concept that the class represents This class lacks cohesion: public class CashRegister{ public void enterPayment(int dollars, int quarters, int dimes, int nickels, int pennies)... public static final double NICKEL_VALUE = 0.05; public static final double DIME_VALUE = 0.1; public static final double QUARTER_VALUE = 0.25;... }

10 Cohesion Solution: Make two classes: public class Coin { public Coin(double aValue, String aName){... } public double getValue(){... }... } public class CashRegister { public void enterPayment(int coinCount, Coin coinType) {... }... }

11 Coupling A class depends on another if it uses objects of that class CashRegister depends on Coin to determine the value of the payment Coin does not depend on CashRegister High Coupling = many class dependencies Minimize coupling to minimize the impact of interface changes To visualize relationships draw class diagrams UML: Unified Modeling Language. Notation for object- oriented analysis and design

12 Side Effects Side effect of a method: any externally observable data modification public void transfer(double amount, BankAccount other){ balance = balance - amount; other.balance = other.balance + amount; // Modifies explicit parameter } Updating explicit parameter can be surprising to programmers; it is best to avoid it if possible

13 Side Effects Another example of a side effect is output public void printBalance(){ // Not recommended System.out.println("The balance is now $"+balance); } Bad idea: message is in English, and relies on System.out It is best to decouple input/output from the actual work of your classes You should minimize side effects that go beyond modification of the implicit parameter

14 Call by Value and Call by Reference Call by value: Method parameters are copied into the parameter variables when a method starts Call by reference: Methods can modify parameters Java has call by value A method can change state of object reference parameters, but cannot replace an object reference with another public class BankAccount{ public void transfer(double amount, BankAccount otherAccount){ balance = balance - amount; double newBalance = otherAccount.balance + amount; otherAccount = new BankAccount(newBalance); // Won't work } }

15 Scope of Class Members An unqualified instance field or method name refers to the this parameter public class BankAccount{ public void transfer(double amount, BankAccount other){ withdraw(amount); // i.e., this.withdraw(amount); other.deposit(amount); }... }

16 Overlapping Scope A local variable can shadow a field with the same name Local scope wins over class scope public class Coin{... public double getExchangeValue(double exchangeRate) { double value; // Local variable... return value; } private String name; private double value; // Field with the same name } Access shadowed fields by qualifying them with the this reference value = this.value * exchangeRate;

17 Event driven programs Many things may happen: Pressing a button Selecting values with sliders, lists etc. Type text in fields Mouse clicks on a canvas Timers Menus Window closing, resizing

18 JEventQueue My little trick… Usual event-driven programming in Swing requires: Inheritance Interface Inner classes

19 JEventQueue JEventQueue events = new JEventQueue(); events.listenTo(button1,"button1"); events.listenTo(button2,"button2");... while(true){ EventObject event = events.waitEvent(); String name=events.getName(event); if(name.equals("button1")){... }else if(name.equals("button2")){... }else... }

20 Example

21 Event loop JEventQueue events=new JEventQueue(); events.listenTo(button1,"celcius"); events.listenTo(button2,"fahrenheit"); while(true){ EventObject event=events.waitEvent(); String name=events.getName(event); if(name.equals("celcius")){ double f=Double.parseDouble(field2.getText()); field1.setText(""+(f-32)/1.8); }else if(name.equals("fahrenheit")){ double c=Double.parseDouble(field1.getText()); field2.setText(""+(c*1.8+32)); }

22 Selections: RadioButton: isSelected() CheckBox: isSelected() Spinner: getValue() Slider. getValue() ComboBox: getSelectedItem() List: getSelectedValue()

23 Text components Generate lots of events: You press ’a’ Key pressed event Key typed event Text field changed event Key released event

24 Text Components Ignore most of them except: Typing a key that corresponds to a character Pressing a control key: Arrows, Page up/down, function keys etc.

25 Mouse events Draw circles where you click and lines where you drag. int x0=0,y0=0; while(true){ EventObject event=events.waitEvent(); if(events.isMouseEvent(event)){ int x=events.getMouseX(event); int y=events.getMouseY(event); if(events.isMousePressed(event)){x0=x;y0=y;} if(events.isMouseClicked(event)) canvas.drawOval(x0-5,y0-5,10,10); if(events.isMouseReleased(event)) canvas.drawLine(x0,y0,x,y); }

26 Timers startTimer(miliseconds,name) stopTimer(name)

27 Menus frame.setJMenuBar( events.jmenubar(new Font("Arial",Font.PLAIN,18), events.jmenu("File",'F’, events.jmenuitem("New",'n',events.control('N')), events.jmenuitem("Open",'o',events.control('O')), events.jmenuitem("Save",'s',events.control('S')), events.jmenuitem("Save as",'a', events.control('A')), events.jmenuitem("Exit",'x',events.control('Q')) ), events.jmenu("Edit",'E',.. ), events.jmenu("View",'V', )

28 Menus

29 Mnemonic: Press Alt-F to get File menu then press ’s’ to save Accelerator key: Press Control-s to save

30 Window events Events when closing or resizing a window Bring up a dialog when you close a window so that the user can confirm whether the user wants to exit the program. Force exit of a program: call System.exit(0);


Download ppt "Computer Science A 8: 6/3. Group data in an object class PlayerData{ String name; int score; }.. PlayerData d=new PlayerData(); d.name=“Mads”; d.score=100;"

Similar presentations


Ads by Google