Download presentation
Presentation is loading. Please wait.
1
Java Classes, Objects, and Events: A Preview
Methods TM Maria Litvin Gary Litvin An Introduction to Object-Oriented Programming The Ramblecs case study in this chapter is rich enough to illustrate the main OOP concepts and give students some material for fun exercises. Java Classes, Objects, and Events: A Preview Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
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 This chapter gives an introduction to the main Java and OOP concepts but does not require their full understanding. In terms of grasping the big picture, each student proceeds at his or her own pace. The same concepts are covered later in more depth. Here students get a general idea of how things are put together, get a feel for OOP, and work on exercises that require rearranging small pieces of code.
3
Objects in the Ramblecs Applet
Ramblecs, the applet itself FallingCube cube LetterPanel whiteboard Class names start with a capital letter, while object names start with a lowercase letter. This is a stylistic convention, not strictly required by Java. The string of letters in the FallingCube class is also an object; its name is letters and its class is String. Other objects are used in the program, e.g., Timer t, ActionEvent e. JButton go
4
Classes and Source Files
A class defines a class of objects. Class name: File name: Convention: a class name starts with a capital letter SomeClass Ramblecs FallingCube SomeClass.java Ramblecs.java FallingCube.java In the Unix operating system, where Java started, file names are case sensitive. In Windows the names can use upper- and lowercase letters, but names that differ only in case are deemed the same. But javac and java still care. Note that in command-line use of SDK, javac takes a file name SomeThing.java, while java takes a class name SomeThing (no extension). We will talk more about stylistic conventions vs. the required Java syntax in Chapter 5. Same upper / lower case letters
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 In OOP, the correct attitude is reusability: “Where can I find the needed code already written?” not “What is the best way to write this code?” But don’t try this with your homework.
6
Classes in the Ramblecs Applet
An arrow from A to B indicates that A uses B: either creates an object of this type or calls its methods. In other words, A won’t compile if it can’t find B in the current project folder, along classpath, or in the library. An applet always has one “main” class that extends JApplet and has an init method. But it does not have the main method. It is very easy to convert an applet into an application by slightly changing this “main” class: 1. Change extends JApplet to extends JFrame 2. Add a constructor: public Ramblecs() { super ("The Ramblecs Game"); // Calls JFrame’s // constructor to add the title bar init(); } 3. Add main: public static void main(String[] args) JFrame window = new Ramblecs(); window.addWindowListener(new ExitButtonListener()); window.setBounds(100, 50, 160, 310); // x0, y0, width, height window.show(); From the library package javax.swing Written by us
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. Even if you are using an IDE, you have to learn to use Windows Explorer (or Mac folders) to copy, move, and delete files. When you run applets from the book, you have to make sure that the HTML file is in the same folder as the class files (or add the codebase attribute to the <applet> tag). An IDE usually allows you to tell it where to put class files.
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 Go to Java API docs ( and examine the list of packages in the upper-left corner. We will mostly use classes from java.lang, java.util, java.awt, java.awt.event, and javax.swing.
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"); A package name implies the location of the class files in the package. For example, java.awt.event implies that the classes are in the java/awt/event subfolder. In reality, packages are compressed into .jar files that have this path information for classes saved inside. A .jar file is like a .zip file; in fact, it can be opened with the pkzip program that normally reads and creates .zip files. import is simply a substitution directive that says: Whenever you see JButton, treat it like javax.swing.JButton. No files are moved or included. If you want a parallel to C++, import is more like #define than #include. Fully-qualified name
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 Some programmers do not like .* and prefer to list all imported classes individually. Once the number of library classes used becomes large, this becomes too tedious. It is also harder to change the class: you need to add import statements for each library name added.
11
public class SomeClass {
Attributes / variables that define the object’s state. Can hold numbers, characters, strings, other objects. Usually private. Fields Constructors Methods Code for constructing a new object and initializing its fields. Usually public. Some programming languages (Pascal, e.g.) distinguish between functions and procedures. A function performs a calculation and returns the resulting value. A procedure does something but does not return any value. In Java, a method is like a function, but it can be declared void, meaning it does not return any value. A constructor is like a special procedure for constructing an object. It has no return value and it is not even declared void. Other than that, constructors are similar to methods. Actions that an object can take. Can be public or private. } private: visible only inside this class public: visible in other classes
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 The name of a constructor is always the same as the name of the class. Constructor The name of the constructor is the same as the name of the class, so it starts with a capital letter. The programmer gives names to fields and methods. Style: by convention, the names of methods and fields start with a lowercase letter. Names of fields should sound like nouns, and names of methods should sound like verbs. Methods }
13
Fields private (or public) [static] [final] datatype name;
You name it! private (or public) [static] [final] datatype name; Usually private May be present: means the field is a constant May be present: means the field is shared by all objects in the class More on syntax for declaring fields in Chapter 6. Programmers strive to make their programs readable. One of the important tools in this struggle is to give meaningful names to classes, fields, variables, and methods: not too short, not too long, and descriptive. int, double, etc., or an object: String, JButton, FallingCube, Timer
14
Fields (cont’d) May have primitive data types: int, char, double, etc.
private int cubeX, cubeY; // cube coordinates ... private char randomLetter; // cube letter There are other built-in primitive data types: long, float, double, etc; more in Chapter 6. String is built in but not “primitive”; a String is an object. Primitive types do not have constructors/methods; objects belong to classes that do. Some OOP purists consider it an unfortunate compromise that Java (like C or C++) has primitive data types. They believe that in an OOP language everything should be an object, even a number. Java has Character, Integer and other classes that parallel primitive data types. These can “wrap around” primitive types when you need to treat them as objects.
15
Fields (cont’d) May be objects of different types:
private FallingCube cube; private Timer t; private static final String letters; If a field is an object, you need to create or initialize that object, either in the declaration itself or in the class’s constructor or one of the methods. It is null by default.
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. It is usually a good idea to provide a so-called “no-args” constructor that takes no arguments. If no constructors are supplied at all, then Java provides one default no-args constructor that only allocates memory for the object and initializes its fields to default values (i.e., numbers to zero, booleans to false, objects to null). A class may have only one no-args constructor. In general, two constructors for the same class with exactly the same number and types of arguments cannot coexist.
17
Constructors (cont’d)
JButton’s constructors (from API docs, Release 1.3). JButton has five constructors; when we created the “Go” button we used the fourth one: the one that takes a string as an argument and displays it on the button. go = new JButton("Go");
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 Some library methods return new objects, but these methods still have the new operator hidden in them. One exception is literal strings: text in double quotes creates a String object and it is just there; no new is needed. Calls Timer’s constructor with delay and this (i.e. this object) as the parameters (see Java docs for javax.swing.Timer)
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); charAt is a String method. As the capital M in “Math” indicates, Math is a class, not an object. (That’s what naming conventions are for.) There are no objects of the Math type: all the methods are class methods. A class may have both static (class) and non-static (instance) methods.
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/private designations help to isolate programmers from each other: one programmer needs to know little about other programmers’ classes: only their public interface. Even if the same programmer writes two classes, they are isolated from each other. If a change in private fields or methods occurs, then only that class has to change; other classes are not affected. This is called “information hiding.” public method public method
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 ) {...} Methods in different classes may have the same name. Two methods in the same class may have the same name, too, but then they must differ in the number or types of arguments. Then the compiler figures out which one to call. These are called “overloaded methods.”
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, message received, etc.) Can originate in your program (a timer fires, a panel needs to be repainted, etc.) In a console application, things happen in an orderly fashion: prompt - response - result. So such programs can be controlled in a sequential manner. In a GUI application, different types of events may occur in any order. So we need “listeners” that respond to specific events.
23
Events (cont’d) Click! 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 Some types of listeners may have several methods. For example, MouseListener has five methods: mousePressed, mouseReleased, mouseClicked, mouseEntered, and mouseExited. An ActionListener, used here with the “Go” button, requires only one method, actionPerformed.
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. To serve as an action listener, the object must belong to a class that “implements” ActionListener and has an actionPerformed method. In this example the applet itself serves as a listener. We could define a separate class whose object would serve as an action listener for the button. A button or another GUI component may have several action listeners attached to it. Then each one of the listeners will be activated when an event occurs. Describes the details of this event. Not used here.
25
Ramblecs Events Ramblecs class applet object
creates the whiteboard panel and the “Go” button calls whiteboard’s dropCube Applet starts init method “Go” clicked So the Ramblecs class has two methods, init and actionPerformed, but we never call them explicitly. The first is called when the applet starts, the second is called whenever the “Go” button is clicked. actionPerformed method
26
Ramblecs Events (cont’d)
LetterPanel class whiteboard object starts the timer and the cube moves the cube down; generates a repaint request restores the background; calls cube’s draw method dropCube method Timer fires actionPerformed method We do explicitly call the dropCube method in the LetterPanel class. But we never call paintComponent directly; we call repaint() instead. repaint issues a repaint event, and this event eventually triggers a call to paintComponent. The type of an event and a listener is the same for a Timer as for a JButton: ActionEvent and ActionListener. Here the whiteboard object itself serves as a listener for the Timer t. Repaint request paintComponent method
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 The FallingCube object cube does not respond directly to events: its methods are called by other objects as necessary. draw method
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? How many classes did we write for Ramblecs? Three: Ramblecs, LetterPanel, and FallingCube. Name a few library classes that we used. JButton, JPanel, Timer. What are import statements used for? To be able to use short names for library classes instead of fully-qualified names. What is a field? A constructor? A method? A field is a data item in an object. A field describes an attribute or a variable value in an object. A constructor is like a method for creating objects of the class. A method is a fragment of code that performs a certain calculation or task and can be called from other constructors and methods. (In the case of a recursive method, it also calls itself.) Which operator is used to construct an object? new What is the difference between private and public methods? Private methods can be called only from constructors or methods of the same class. Public methods can be called from other classes as well. Why are fields usually private? Because fields are more prone to change than are rules for calling constructors and methods. If a field changes, we want to be sure that other classes are not affected.
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 ( ) ); Define an event-driven application. In an event-driven application, some methods are called in response to events, which may occur in any sequence. Why are GUI applications event-driven? Because different GUI components (menus, buttons, sliders, etc) can be activated in any order. Is an event listener a class, an object, or a method? An object. How many action listeners are used in Ramblecs? Two: one for the “Go” button and one for the timer. What does the following statement do? w.addWindowListener (new ExitButtonListener()); It creates a new object of the ExitButtonListener type and adds it to w as a WindowListener. This is necessary to handle events from the “close window” button (a little X button in the upper-right corner) because JFrame does not “listen” to this button by default (i.e., ignores its events) and later releases of the SDK have an option to activate this button when you define a JFrame object, so our own ExitButtonListener is not needed.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.