CS136, Lecture 3

    1. More Java
      1. Visibility declarations
      2. How do you create an object?
      3. Objects as references
      4. Garbage Collection
      5. Subtypes
      6. Casting values
    2. Applets
      1. Applet life cycle:
    3. CS136 Graphics Library
    4. Java GUI components
      1. Buttons
    5. Event-driven programming in Java

More Java


Visibility declarations

Declare visibility of fields & methods: Fields should always be protected (or private).

Only declare method public if intended to be used by clients (external objects)

Notice can refer to instance variables within methods without passing as parameters (global to class). Can also refer to instance variables as components of "this". E.g., this.top

Keyword "this" refers to object executing method

Notice HourlyEmployee and ExemptEmployee declared as subclasses using "extends".

How do you create an object?

If have variable declared: Employee myEmployee;

then create via myEmployee = new Employee(...);

where Employee(...) is a constructor for Employee class.

Constructor must have same name as class

Constructors can be overloaded so can handle different collections of parameters.

Note distinction between "static" and "dynamic" type of object.

If variable declared with a static type of, say "Employee", but want to instantiate as "HourlyEmployee", then write:

		myEmployee = new HourlyEmployee(...);
In general can always use object of a subclass in place of object of superclass.

Objects as references

Objects are actually held as "references" - implicit pointers.

Equality test (==) tests if identical references,

Assignment leads to sharing - two variables pointing to same object!

I.e., if fst, snd : Employee, and execute: fst = snd;

then change to fst.Name will change snd.Name.

Typically create a new object using a class constructor or use clone method inherited from Object (see pg 64 of text).

Object also has equals method.

Unfortunately clone always returns Object, which is superclass of all other classes.

Must downcast in order to actually use it & might throw exception.

Talk about in more detail later when discuss exceptions.

Garbage Collection

Never have to dispose of objects! Garbage collector automatically disposes of objects when they are no longer accessible from program.

Subtypes

Object of subclass can be used where expect an object of superclass.

Can assign an object of subclass to variable of superclass (but not vice-versa).

Can also pass an object of subclass as parameter where expect object of superclass.

E.g.

public void DoSomething(Employee thisEmployee,... );
begin
        :
    System.out.println(thisEmployee.GetName() + " makes " +
                        thisEmployee.GetWkPay());
        :
end;
If pass in a parameter of class Employee, then print out 0.

If pass in a parameter of class HourlyEmployee, then print out 40 * HourlySalary.

If pass in a parameter of class ExemptEmployee, then print out yearlySalary / 52.

Uses dynamic method-lookup of message to find corresponding method of object.


Casting values

Can assign from subclass to superclass:

E.g., if emp is type Employee, hEmp is type HourlyEmployee, then can write:

    emp = hemp;
    hEmp = emp ;        // Illegal assignment - won't compile! 
    hEmp = (HourlyEmployee) emp;  // example of downcast
        // Ok if emp is really HourlyEmployee, raises exception o'wise
    if (emp instanceof HourlyEmployee) then  
        // Safer alternative - check before casting!
        hemp = (HourlyEmployee)emp;  
    emp.setHourlyPay(6.25f)     // illegal even if emp is HourlyEmployee
    ((HourlyEmployee)emp).setHourlyPay(6.25f)  // OK since did cast

Applets

We will tend to use Applets rather than applications in this course.

Applets are executable from within web browser. Live on web page.

Can draw on applets - we'll use classes from graphics library and can add predefined GUI (graphic user interface) components to applet.

Applet life cycle:

Methods: If no interaction with environment then can consider start() as the main program and call other methods from there.

Calling paint problematic since usually don't have Graphics object in hand. Instead call repaint(); which invokes "update" method (passing it a Graphics object).

The update method erases any drawing done previously and then calls paint with the Graphics object.

CS136 Graphics Library

Provided a library of graphics commands to allow simple drawing on applets or other components.

Java code for library can be found in CS136 folder on Cider Press. Documentation is available from the CS136 web page.

Interface Renderable provides common interfaces for all classes in the library.

Abstract class RenderAbsClass gives part of the implementation that is common to all classes.

Now see Rect, Oval, etc. Notice Rect is superclass of other 2-dim'l classes (but not Line or DrawableString).

Look at SimpleGraphicsApp in which all painting is done in paint() method.

Note never call paint directly yet it is invoked when program starts up and when screen needs refreshing.

Java GUI components

Include labels, text fields, buttons, etc. (all part of java.awt)

Buttons

For example, Button is class of buttons.

Constructor is:

	public Button(String label);
when executed creates a button with "label" printed on it. Generally large enough to display label.

Responds to variety of messages. One of most useful is

	public void setBackground(Color buttonColor);
which changes color of button.

Color is predefined class with many constants representing colors:

Can also create own new colors with Color constructor (see documentation)

Add a button to an applet by writing:

	add(startButton);
This will normally result in button being added to applet in first available space starting from top left and working across from left to right (and then trying next row, etc.)

Button generates an event when user clicks on it.

Event-driven programming in Java

Usually programs based on interaction with user through pressing buttons, mouse clicks or drags, key presses, etc.

Method "action" is executed whenever there is an event (and no other routine executing)

	public boolean action(Event evt, Object obj);
Event has a number of fields which can be used to identify the kind of event. One of simplest things to do is to identify the object involved with the action by examining the "target" field.

E.g., if Button startButton = new Button("start");

then can write

	if (evt.target = startButton)
		doStart();
See program buttons for simple example.

Look at program bouncing ball to see use of button and graphics objects from library.