Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
CS180 Recitation
More about Objects and Methods
Announcements
• Project3 issues– Output did not match sample output.– Make sure your code compiles. Otherwise it
cannot be graded.– Pay close attention to file names, have them
match expected names.– Thoroughly test before submitting.
Operation Overloading• It is sometimes useful to have two methods of the same
name but accept different parameters (very common in Math library)
• May not differ only by return type or variable name• Constructors can be overloaded like other methods
Valid:public String f(int x) {…}public String f(double x) {…}public String f(float f) {…}Invalid:public int f(int x) {…}public double f(int x) {…}
Default Constructors
• If you dont write your own, Java will provide one for you.
• Write your own!– Good programming practice
• Use mutators to modify class variables.– Better code reuse.– Single point of error.
Copy Constructors and Memory Management
• Copy constructors are useful in making a deep copy of an object– Shallow copy: simple reference assignment
with “=“ (what problems may crop up?)– Deep copy: copy over all values and objects
(deep copy usually) explicitly into new memory
Memory Managementpublic class A {
private int x;
public A() { x=0; }public A(int x) { set(x); }public A(A a) { x = a.get(); }
public void set(int x) { this.x = x; }public int get() { return x; }
}
A a1 = new A();A a2 = new A(2);a1 = a2;a2.set(3);A a3 = new A(a1);a1.set(4);
a1.get()?a2.get()?a3.get()?
static keyword• Useful for methods which do not need to access class
variables or methods– Called using the class name– Think: Math library
• Used for class variables which are shared over instances of the class
class A {private static int a;
public void setA(int x) {a = x;
}
public int getA() {return a;
}}
A a1 = new A();A a2 = new A();a1.setA(5);System.out.println(“a: “+a2.getA());
static Memory Managementpublic class A {
private static int x;
public A() { x=0; }public A(int x) { set(x); }public A(A a) { x = a.get(); }
public static void set(int x) { this.x = x; }public static int get() { return x; }
}
A a1 = new A();A a2 = new A(2);a1 = a2;A.set(3);A a3 = new A(a1);a1.set(4);a3.set(1);
a1.get()?a2.get()?a3.get()?
null keyword
• Indicates the non-existence of an object (think address 0x00000000)
• Can be used to represent any object type• A null object can NOT call any methods
– This will result in a runtime error called a NullPointerException
– Get in the habit of checking against the null object!
null Memory Managementpublic class A {
private int x;
public A() { x=0; }public A(int x) { set(x); }public A(A a) { x = a.get(); }
public void set(int x) { this.x = x; }public int get() { return x; }
}
A a1 = null;a1 = new A();A a2 = new A(a1);A a3 = null;if (a3 == null)
a3 = new A();else
a3.set(3);a1.set(4);
a1.get()?a2.get()?a3.get()?
Pass-By-Value
public class A {
private int x;
public A() { x=0; }public A(int x) { set(x); }public A(A a) { x = a.get(); }
public static void reset(A a) { a = new A(); }public void set(int x) { this.x = x; }public int get() { return x; }
}
A a1 = new A();a1.set(4);A.reset(a1);
a1.get()?
Parameters in Java are passed by value (as opposed to pass by reference).
12
Wrapper Classes
• Recall that arguments of primitive type treated differently from those of a class type– May need to treat primitive value as an object
• Java provides wrapper classes for each primitive type– Methods provided to act on values
• Java library methods work with Objects, not Promitives.
13
Wrapper Classes• Allow programmer to have an object that
corresponds to value of primitive type• Contain useful predefined constants and
methods• Wrapper classes have no default
constructor– Programmer must specify an initializing value
when creating new object• Wrapper classes have no set methods
14
Testing Methods
• To test a method use a driver program– Example – code in listing 6.13
• Every method in a class should be tested• Bottom-up testing
– Test code at end of sequence of method calls first
• Use a stub – simplified version of a method for testing purposes– Used in top-down testing
file:///Users/salman/CS/Purdue/cs180/Fall08/Recitations/10-2/CodeSamples3.htm
15
Adding Buttons
• Create object of type Jbutton– Then add to content pane
• Possible to associate an action with a button
• View applet example, listing 6.21class PreliminaryButtonDemo
file:///Users/salman/CS/Purdue/cs180/Fall08/Recitations/10-2/CodeSamples3.htm
16
Adding Buttons
• Applet Output
If the user clicks either of these buttons, nothing
happens.
17
Event-Driven Programming
• Applets use events and event handlers• An event
– An object that represents some user action which elicits a response
– Example: clicking on button with mouse• Listener objects are specified to receive
the events– Listener objects have event handler methods
18
Event-Driven Programming
• Figure 6.6 Event firing and an event listener
This event object is the result of a button click. The event object goes from the
button to the listener.
This listener object performs some action, such as making text visible in the applet, when
it receives the event object.
19
Programming Buttons
• When an event is "sent" to the listener object …– A method of the listener object is invoked– The event object is given to the listener object
method as the argument• For each button
– Specify the listener object (register the listener)
– Methods to be invoked must be defined
20
Programming Buttons
• Figure 6.7 Buttons and an action listener
21
Programming Buttons• Buttons fire events as objects of class ActionEvent
• Event objects handled by action listeners• To make a class an action listener
– Add phrase implements ActionListener to heading of class definition
– Register the action listener by invoking addActionListener
– Add definition named actionPerformed to class
22
Programming Buttons
• To be an action listener, a class must have– A method named actionPerformed– The method has a parameter of type ActionEvent
– This is the only method required by the ActionListener interface
• Syntax
23
Programming Example
• A Complete Applet with Buttons• View applet code, listing 6.22class ButtonDemo
• Note features– Specification implements ActionListener– Invocation of addActionListener– Method actionPerformed
file:///Users/salman/CS/Purdue/cs180/Fall08/Recitations/10-2/CodeSamples3.htm
24
Programming Example
• Initial applet output
25
Programming Example
• Applet output after clicking Sunny
26
Programming Example
• Applet output after clicking Cloudy
27
Adding Icons
• An icon is a picture– Usually small (but not necessarily)– Often a .GIF or .JPEG file– Picture file stored in same folder as program
• Icon can be added to a label, button, or other component
• Class ImageIcon used to convert digital image to icon
28
Adding Icons
• View sample applet, listing 6.23class IconDemo
• Note– Creation of icon– Attaching
icon to label
Sample screen output
29
Adding Icons
• Figure 6.8 A button containing an icon
30
Changing Visibility
• Components have a method named setVisible– Changes component from visible to invisible
(or the other way)• An invisible component is considered not
there– Thus an invisible button would be inoperable
31
Programming Example
• An Example of Changing Visibility• View sample applet, listing 6.24class VisibliityDemo
file:///Users/salman/CS/Purdue/cs180/Fall08/Recitations/10-2/CodeSamples3.htm
CS180 RecitationAnnouncementsOperation OverloadingCopy Constructors and Memory ManagementSlide 5Memory Managementstatic keywordstatic Memory Managementnull keywordnull Memory ManagementPass-By-ValueWrapper ClassesSlide 13Testing MethodsAdding ButtonsSlide 16Event-Driven ProgrammingSlide 18Programming ButtonsSlide 20Slide 21Slide 22Slide 23Slide 24Slide 25Slide 26Adding IconsSlide 28Slide 29Changing VisibilitySlide 31