February 9 - 13, 2009

advertisement
February 9 - 13, 2009
 2/9:
Go over Exam 1
 2/11: Makeup exam for Exam 1
 2/20: Exam 2 Review Sheet Available in
Lecture
 2/27: Lab 2 due by 11:59:59pm
 3/2: Exam 2
 3/4: Go over Exam 2
 3/6: Exam 2 Makeup
public returnType nameOfMethod() {
}
returnType is the type of information that is
returned from this method – void if nothing
returned
nameOfMethod is the name that the
programmer picks for this method
() is called a parameter list when we write
the definition of a method – tells us what
information is needed to complete the work
of the method
 First,
we create the file CSE113Picture.java
and put inside the class definition:
public class CSE113Picture {
}
 We
want to be able to do the following at
the interactions pane:
> CSE113Picture p = new
CSE113Picture();
> p.show();
 And
we want there to be an image shown.
Therefore, we need to bring up the dialog to
have the user pick an image file and then
create a Picture object and then show it.
 In
order to have the file dialog and picture
created when we create a CSE113Picture, we
need to use a special method that gets called
whenever an object is created.
 This method is called a constructor and its
job is to set the initial state of the object.

When we add the constructor to the class
definition, we get:
public class CSE113Picture {
public CSE113Picture() {
}
}

The constructor definition is like a method
definition except:


It does not have a return type
The name of the constructor is the same as the name
of the class
 We
want to put the code for getting the file
dialog and creating the picture. The code
inside the constructor for doing this will look
basically the same as the code we wrote at
the interactions pane.
public class CSE113Picture {
public CSE113Picture() {
Picture p = new
Picture(FileChooser.pickAFile());
}
}
 Now,
when we create a CSE113Picture, we
get the file dialog and a picture gets
created.
 Next, all we need to do is “show” the image
the user selected.
 We need to write a method to show the
picture.
public class CSE113Picture {
public CSE113Picture() {
Picture p = new
Picture(FileChooser.pickAFile());
}
public void show() {
p.show();
}
}
is not recognized outside of the
constructor.
 Variables declared inside a method are not
accessible to other methods (even if those
methods are in the same class).
p
 Create
a class-level variable that is
accessible within the entire class.
 These kinds of variables are also called
instance variables.
 Declaring an instance variable is the same as
declaring any variable except the keyword
private is placed in front.
public class CSE113Picture {
private Picture _pic;
public CSE113Picture() {
_pic = new
Picture(FileChooser.pickAFile());
}
public void show() {
_pic.show();
}
}
 Now,
when we create a CSE113Picture and
call the show method on it, we can see the
picture the user chooses.
Download