Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented...

Preview:

Citation preview

Java Classes, Objects, and Events: A Preview

JavaJavaMethodsMethods

An Introductionto Object-Oriented Programming

Maria Litvin

Gary Litvin

Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

TM

4

C

H A P

T E R

4-2

Objectives: Get an introduction to classes, objects, fields,

constructors, and methods; get a general idea of how a small program is put together

Explore how library classes are used in Java programs

Get a feel for how methods call each other; learn about private and public methods

Learn a little about event-driven applications and the event-handling mechanism in Java

4-3

Objects in the Ramblecs Applet

Ramblecs, the applet itself

LetterPanel whiteboard

FallingCube cube

JButton go

4-4

Classes and Source Files

A class defines a class of objects.

Class name: File name:

SomeClass

Ramblecs

FallingCube

SomeClass.java

Ramblecs.java

FallingCube.java

Convention:

a class name starts with a capital letter

Same upper / lower case letters

4-5

Programmers write classes

And extensively use library classes

– either directly:

JButton go = new JButton("Click here");

– or through inheritance:

public class LetterPanel extends JPanel

4-6

Classes in the Ramblecs Applet

Ramblecs (applet)

FallingCube cube

LetterPanel whiteboard JButton go

Written by us

From the library package javax.swing

4-7

Files and Folders javac automatically looks for classes (.java or .class

files) in the current folder, or, if classpath is set, in folders listed in the classpath string.

A missing file may be reported as a syntax error when compiling another file.

If you set classpath, include the current folder. It is denoted by a dot. For example:

.;C:\javamethods\EasyIO

IDE helps take care of the file locations.

4-8

Libraries Java programs are usually not written from

scratch.

There are hundreds of library classes for all occasions.

Library classes are organized into packages. For example:

java.util — miscellaneous utility classes java.awt — windowing and graphics toolkit javax.swing — newer GUI package Swing

4-9

import Full library class names include the package

name. For example:

java.awt.Color javax.swing.JButton

import statements at the top of your program let you refer to library classes by their short names:

import javax.swing.JButton; ... JButton go = new JButton("Click here");

Fully-qualified name

4-10

import (cont’d) You can import names for all the classes in

a package by using a wildcard .*:

import java.awt.*; import java.awt.event.*; import javax.swing.*;

java.lang is imported automatically into all classes; defines System, Math, Object, String, and other commonly used classes.

Imports all classes from awt, awt.event, and swing packages

4-11

public class SomeClass{

Fields

Constructors

Methods

}private: visible only inside this class

public: visible in other classes

Attributes / variables that define the object’s state. Can hold numbers, characters, strings, other objects. Usually private.

Code for constructing a new object and initializing its fields. Usually public.

Actions that an object can take. Can be public or private.

4-12

public class FallingCube{

private final int cubeSize;private int cubeX, cubeY; // Cube coordinates...private char randomLetter; // Cube letter

public FallingCube(int size){ cubeSize = size; ...}

public void start(){ cubeX = 0; cubeY = -cubeSize; ...}...

}

Fields

Constructor

Methods

The name of a constructor is always the same as the name of the class.

4-13

private (or public) [static] [final] datatype name;

Fields

Usually private

May be present: means the field is shared by all objects in the class

May be present: means the field is a constant

int, double, etc., or an object: String, JButton, FallingCube, Timer

You name it!

4-14

Fields (cont’d) May have primitive data types:

int, char, double, etc.

private int cubeX, cubeY; // cube coordinates...private char randomLetter; // cube letter

4-15

Fields (cont’d)

May be objects of different types:

private FallingCube cube;private Timer t;private static final String letters;

4-16

Constructors Constructors are like methods for creating

objects of a class.

Most constructors initialize the object’s fields.

Constructors may take parameters.

A class may have several constructors that differ in the number or types of their parameters.

All of a class’s constructors have the same name as the class.

4-17

Constructors (cont’d)

go = new JButton("Go");

4-18

Constructors (cont’d) Call them using the new operator:

cube = new FallingCube(CUBESIZE);

...

t = new Timer(delay, this)

Calls FallingCube’s constructor with CUBESIZE as the parameter

Calls Timer’s constructor with delay and this (i.e. this object) as the parameters (see Java docs for javax.swing.Timer)

4-19

Methods Call them for a particular object:

cube.start();

whiteboard.dropCube();

randomLetter = letters.charAt(i);

But call static (“class”) methods for the whole class, not a specific object:

y = Math.sqrt (x);

4-20

Methods (cont’d) Constructors and methods can call other

public and private methods of the same class.

Constructors and methods can call only public methods of another class.

Class X

private method

Class Y

public method public method

4-21

Methods (cont’d) You can call methods with specific arguments:

g.drawRect (75, 25, 150, 50); g.drawString ("Welcome", 120, 50);

The number and types of arguments must match the method’s parameters:

public void drawRect ( int x, int y, int width, int height ) {...}

public void drawString ( String msg, int x, int y ) {...}

4-22

Events Can originate in the real world (mouse

clicked, keyboard key pressed, cable gets connected, etc.)

Can come from the operating system (window resized or closed, e-mail message received, etc.)

Can originate in your program (a timer fires, a panel needs to be repainted, etc.)

4-23

Events (cont’d) An object that

generates events may have one or several listeners attached to it.

A listener is an object.

A listener’s method is called for each event.

ActionListener object

(ActionEvent e){ whiteboard.dropCube();}

public void actionPerformed

Click!

4-24

Events (cont’d)public class Ramblecs extends JApplet implements ActionListener{ ... private JButton go;

public void init() { go = new JButton("Go"); go.addActionListener(this); ... }

public void actionPerformed(AcionEvent e) { whiteboard.dropCube(); }}

Add a listener to the button. In this case, the listener object is the applet itself.

Describes the details of this event. Not used here.

4-25

Ramblecs Events

Ramblecs classapplet object

creates the whiteboard panel and the “Go” button

calls whiteboard’s dropCube

Applet starts init method

actionPerformed method “Go” clicked

4-26

Ramblecs Events (cont’d)LetterPanel classwhiteboard object

starts the timer and the cube

moves the cube down; generates a repaint request

restores the background; calls cube’s draw method

Repaint request

dropCube method

actionPerformed methodTimer fires

paintComponent method

4-27

Ramblecs Events (cont’d)FallingCube class

cube object

picks a random letter; resets cube’s position to the top

checks whether cube reached the bottom; moves the cube down

draws the cube

start method

moveDown method

draw method

4-28

Review: How many classes did we write for Ramblecs? Name a few library classes that we used. What are import statements used for? What is a field? A constructor? A method? Which operator is used to construct an object? What is the difference between private and

public methods? Why are fields usually private?

4-29

Review (cont’d): Define an event-driven application. Why are GUI applications event-driven? Is an event listener a class, an object, or a

method? How many action listeners are used in

Ramblecs? What does the following statement do?

w.addWindowListener (new ExitButtonListener ( ) );

Recommended