You are on page 1of 90

Chapter 4

Writing Classes
2004 Pearson Addison-Wesley. All rights reserved 4-2
Writing Classes
We've been using predefined classes. Now we will
learn to write our own classes to define objects
Chapter 4 focuses on:
class definitions
instance data
encapsulation and Java modifiers
method declaration and parameter passing
constructors
graphical objects
events and listeners
buttons and text fields
2004 Pearson Addison-Wesley. All rights reserved 4-3
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
Classes
Classes are constructs that define objects
of the same type. (Building plan of similar objects)
A Java class uses variables to define data
fields and methods to define behaviors.
A class provides a special type of methods,
known as constructors, which are invoked
to construct objects from the class.
An object has unique identity
state
behaviors
State(attributes) consists of a set of data fields (properties)
with their current values.
Behavior(operations) of an object is defined by a set of
methods.

data field 1
method n
data field m
method 1
(A) A generic object
...
...
State
(Properties)

Behavior

radius = 5
findArea()
Data field, State
Properties

Method,
Behavior
(B) An example of circle object
Objects
An object has both a state and behavior. The
state defines the object, and the behavior defines
what the object does.

Class Name: Student

Data Fields:
name is _______

Methods:
takeCourse

Student Object 1

Data Fields:
name is Kerem

Student Object 2

Data Fields:
name is Onur


Student Object 3

Data Fields:
name is Meltem


A class template


Three objects of
the Student class
class Planet
{
public double radius;
public String name;
public static final long g = 10;
public void display()
{
System.out.println("Radius "+ radius);
System.out.println("Name " + name);
System.out.println("Long "+ g);

}
public void initialize()
{
radius = 10; //usage
name = "Dunya"; //usage
}
}
class ExPlanet
{
public static void main(String [] args)
{
Planet p = new Planet(); // creation
p. initialize(); //usage
p.display(); //usage

}
}
2004 Pearson Addison-Wesley. All rights reserved 4-8
Classes
A class can contain data declarations and method
declarations
int size, weight;
char category;
Data declarations
Method declarations
Classes

class Circle {
/** The radius of this circle */
double radius = 1.0;

/** Construct a circle object */
Circle() {
}

/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
}

Data field

Method

Constructors

2004 Pearson Addison-Wesley. All rights reserved 4-10
public class CountFlips{
public static void main (String[] args)
{
final int NUM_FLIPS = 1000;
int heads = 0, tails = 0;
Coin myCoin = new Coin();
for (int count=1; count <= NUM_FLIPS;
count++){
myCoin.flip();
if (myCoin.isHeads())
heads++;
else
tails++;
}
System.out.println ("The number flips: " +
NUM_FLIPS);
System.out.println ("The number of heads: "
+ heads);
System.out.println ("The number of tails: " +
tails);
}
}































import java.util.Random;
public class Coin{
private final int HEADS = 0;
private final int TAILS = 1;
private int face;
public Coin (){
flip();
}
public void flip (){
face = (int) (Math.random() * 2);
}
public boolean isHeads (){
return (face == HEADS);
}
public String toString(){
String faceName;
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
}
Output:
The number flips: 1000
The number of heads: 486
The number of tails: 514
4-11
public class Coin{
private final int HEADS = 0;
private final int TAILS = 1;

private int face;

public Coin (){
flip();
}

public void flip () {
face = (int) (Math.random() * 2);
}
public boolean isHeads (){
return (face == HEADS);
}

public String toString(){
String faceName;

if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";

return faceName;
}
}











































public class CoinFlip{
public static void main (String[] args){
Coin myCoin = new Coin();

myCoin.flip();

System.out.println (myCoin);

if (myCoin.isHeads())
System.out.println ("You win.");
else
System.out.println ("Better luck
next time.");
}
}

Output:
Heads
Your Win

































2004 Pearson Addison-Wesley. All rights reserved 4-12
Classes
Well want to design the Die class with other data
and methods to make it a versatile and reusable
resource
Any given program will not necessarily use all
aspects of a given class
See RollingDice.java
See Die.java
2004 Pearson Addison-Wesley. All rights reserved 4-13
public class Die {
private final int MAX = 6; // maximum face
value

private int faceValue; // current value showing
on the die

public Die() {
faceValue = 1;
}

public int roll() {
faceValue = (int)(Math.random() * MAX)+1;

return faceValue;
}

public void setFaceValue (int value) {
faceValue = value;
}

public int getFaceValue() {
return faceValue;
}

public String toString()
{
String result = Integer.toString(faceValue);

return result;
}
}
public class RollingDice{
public static void main (String[] args){
Die die1, die2;
int sum;

die1 = new Die();
die2 = new Die();

die1.roll();
die2.roll();
System.out.println ("Die One: " + die1 + ", Die
Two: " + die2);

die1.roll();
die2.setFaceValue(4);
System.out.println ("Die One: " + die1 + ", Die
Two: " + die2);

sum = die1.getFaceValue() +
die2.getFaceValue();
System.out.println ("Sum: " + sum);

sum = die1.roll() + die2.roll();
System.out.println ("Die One: " + die1 + ", Die
Two: " + die2);
System.out.println ("New sum: " + sum); } }

2004 Pearson Addison-Wesley. All rights reserved 4-14
Output:

Die One: 1, Die Two: 5
Die One: 1, Die Two: 4
Sum: 5
Die One: 1, Die Two: 5
New sum: 6
2004 Pearson Addison-Wesley. All rights reserved 4-15
public class Die2 {
private final int MIN_FACES = 4;

private int numFaces; // number of sides on
the die
private int faceValue; // current value showing
on the die

public Die2 () {
numFaces = 6;
faceValue = 1;
}
public Die2 (int faces) {
if (faces < MIN_FACES)
numFaces = 6;
else
numFaces = faces;

faceValue = 1;
}

public int roll () {
faceValue = (int) (Math.random() *
numFaces) + 1;
return faceValue;
}

public int getFaceValue () {
return faceValue;
}
}
public class SnakeEyes
{
public static void main (String[] args)
{
final int ROLLS = 500;
int snakeEyes = 0, num1, num2;

Die2 die1 = new Die2(); // creates a six-sided die
Die2 die2 = new Die2(); // creates a twenty-sided die

for (int roll = 1; roll <= ROLLS; roll++)
{
num1 = die1.roll();
num2 = die2.roll();
System.out.println("Die 1"+ "\t"+num1+"\t"+"Die
2"+"\t"+ num2);

if (num1 == 1 && num2 == 1) // check for snake eyes
snakeEyes++;
}

System.out.println ("Number of rolls: " + ROLLS);
System.out.println ("Number of snake eyes: " +
snakeEyes);
System.out.println ("Ratio: " +
(float)snakeEyes/ROLLS);
}
}
2004 Pearson Addison-Wesley. All rights reserved 4-16
Output:
Die 1 4 Die 2 5
Die 1 2 Die 2 2
Die 1 2 Die 2 1
Die 1 2 Die 2 3
Die 1 6 Die 2 4
Die 1 1 Die 2 2
Die 1 1 Die 2 2
Die 1 2 Die 2 4
Die 1 3 Die 2 3
Die 1 6 Die 2 1
Die 1 4 Die 2 2
Die 1 2 Die 2 2
Die 1 5 Die 2 1
Die 1 6 Die 2 6
Die 1 2 Die 2 1
Die 1 2 Die 2 3
Die 1 1 Die 2 2
Die 1 1 Die 2 6
Number of rolls: 200
Number of snake eyes: 3
Ratio: 0.015
2004 Pearson Addison-Wesley. All rights reserved 4-17
The Die Class
The Die class contains two data values
a constant MAX that represents the maximum face value
an integer faceValue that represents the current face
value
The roll method uses the random method of the
Math class to determine a new face value
There are also methods to explicitly set and get
the current face value at any time
2004 Pearson Addison-Wesley. All rights reserved 4-18
The toString Method
All classes that represent objects should define a
toString method
The toString method returns a character string
that represents the object in some way
It is called automatically when an object is
concatenated to a string or when it is passed to
the println method
Constructors
Circle() {
}

Circle(double newRadius) {
radius = newRadius;
}
Constructors are a special
kind of methods that are
invoked to perform
initializing actions.
Constructors, cont.
A constructor with no parameters is referred to
as a no-arg constructor.
Constructors must have the same name as
the class itself.
Constructors do not have a return type
not even void.
Constructors are invoked using the new
operator when an object is created. Constructors
play the role of initializing objects.
class Emp
{
private String name;
private String id;
private int salary;
Emp() // default constructor. No argument list
{
name = Ahmet";
id = "1234";
salary = 100;

}
public Emp(String n, String i, int s) // non-default constructor
{
name = n;
id = i;
salary = s;

}
void display()
{
System.out.println("\nEmploye Info ");
System.out.println("Name "+ name);
System.out.println("ID "+ id);
System.out.println("Salary "+ salary);
}
}

class ExEmp
{
public static void main(String [] args)
{
Emp e1 = new Emp();
e1.display();
Emp e4 = new Emp("Ali","98745",
400);
e4.display();
}
}
Creating Objects Using
Constructors
new ClassName();

Example:
new Circle();

new Circle(5.0);

Default Constructor
A class may be declared without constructors.
In this case, a no-arg constructor with an empty
body is implicitly declared in the class. This
constructor, called a default constructor, is
provided automatically only if no constructors
are explicitly declared in the class.
public class Student {
private String name;
private String studentID;
private String surname;
private Course[] takenCourses;
private int state;
public Student(String nameParam,String
surnameParam) {
name=nameParam;
surname=surnameParam;
}
public static void main(String[] args)
{
Student s1 = new
Student(Onur,Saran);
}
}
2004 Pearson Addison-Wesley. All rights reserved 4-27
Data Scope
The scope of data is the area in a program in
which that data can be referenced (used)
Data declared at the class level can be referenced
by all methods in that class
Data declared within a method can be used only in
that method
Data declared within a method is called local data
In the Die class, the variable result is declared
inside the toString method -- it is local to that
method and cannot be referenced anywhere else
2004 Pearson Addison-Wesley. All rights reserved 4-28
Instance Data
The faceValue variable in the Die class is called
instance data because each instance (object) that
is created has its own version of it
A class declares the type of the data, but it does
not reserve any memory space for it
Every time a Die object is created, a new
faceValue variable is created as well
The objects of a class share the method
definitions, but each object has its own data space
That's the only way two objects can have different
states

2004 Pearson Addison-Wesley. All rights reserved 4-29
Instance Data
We can depict the two Die objects from the
RollingDice program as follows:

die1 5 faceValue
die2 2 faceValue
Each object maintains its own faceValue
variable, and thus its own state
Reference Data Fields
The data fields can be of reference types. For
example, the following Student class
contains a data field name of the String type.

public class Student {
String name; // name has default value
null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor
has default value false
char gender; // c has default value
'\u0000'
}
Default Value for a Data Field
The default value of a data field is null for a reference
type, 0 for a numeric type, false for a boolean type,
and '\u0000' for a char type. However, Java assigns no
default value to a local variable inside a method.
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " +
student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
Example
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
Compilation error:
variables not initialized
Java assigns no default value to a local variable
inside a method.
Differences between Variables of
Primitive Data Types and Object
Types


1 Primitive type int i = 1 i
Object type Circle c c reference
Created using new Circle()

c: Circle

radius = 1
Copying Variables of Primitive
Data Types and Object Types

i


Primitive type assignment i = j


Before:


1


j

2

i


After:


2


j

2


c1


Object type assignment c1 = c2


Before:





c2





c1


After:


c2


c1: Circle
radius = 5

C2: Circle
radius = 9







c1: Circle
radius = 5

C2: Circle
radius = 9

Instance
Variables and Methods

Instance variables belong to a specific instance.

Instance methods are invoked by an instance of
the class.
Static Variables, Constants,
and Methods
Static variables are shared by all the instances of the
class.

Static methods are not tied to a specific object.
Static constants are final variables shared by all the
instances of the class.
Static Variables, Constants,
and Methods, cont.

Circle

radius: double
numberOfObjects: int

getNumberOfObjects(): int
+getArea(): double
1
radius
circle1

radius = 1
numberOfObjects = 2

instantiate
instantiate
Memory
2
5
radius
numberOfObjects
UML Notation:
underline: static variables or methods

circle2

radius = 5
numberOfObjects = 2

2004 Pearson Addison-Wesley. All rights reserved 4-38
UML Diagrams
UML stands for the Unified Modeling Language
UML diagrams show relationships among classes
and objects
A UML class diagram consists of one or more
classes, each with sections for the class name,
attributes (data), and operations (methods)
Lines between classes represent associations
A dotted arrow shows that one class uses the
other (calls its methods)
2004 Pearson Addison-Wesley. All rights reserved 4-39
UML Class Diagrams
A UML class diagram for the RollingDice
program:
RollingDice
main (args : String[]) : void
Die
faceValue : int
roll() : int
setFaceValue (int value) : void
getFaceValue() : int
toString() : String
UML Class Diagram(Unified
Modeling Languauge)

Circle

radius: double

Circle()
Circle(newRadius: double)
getArea(): double
circle1: Circle

radius: 10

Class name


Data fields


Constructors and
Methods


circle2: Circle

radius: 25

circle3: Circle

radius: 125

UML Class Diagram


UML notation
for objects


2004 Pearson Addison-Wesley. All rights reserved 4-41
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
2004 Pearson Addison-Wesley. All rights reserved 4-42
Encapsulation
Encapsulation is the technique of making the
fields in a class private and providing access to
the fields via public methods.
If a field is declared private, it cannot be accessed
by anyone outside the class, thereby hiding the
fields within the class. For this reason,
encapsulation is also referred to as data hiding.
The main benefit of encapsulation is the ability to
modify our implemented code without breaking the
code of others who use our code. With this feature
Encapsulation gives maintainability, flexibility and
extensibility to our code.

2004 Pearson Addison-Wesley. All rights reserved 4-43
Encapsulation
An encapsulated object can be thought of as a
black box -- its inner workings are hidden from the
client
The client invokes the interface methods of the
object, which manages the instance data
Methods
Data
Client
2004 Pearson Addison-Wesley. All rights reserved 4-44
public class EncapTest{
private String name;
private String idNum;
private int age;

public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String
newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}
public class RunEncap{

public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " +
encap.getName()+
" Age : "+
encap.getAge());
}
}

Example
Output:

Name : James Age : 20
2004 Pearson Addison-Wesley. All rights reserved 4-45
Benefits of Encapsulation:

1. The fields of a class can be made read-only or
write-only.

2. A class can have total control over what is
stored in its fields.

3. The users of a class do not know how the
class stores its data. A class can change the data
type of a field, and users of the class do not need
to change any of their code.
2004 Pearson Addison-Wesley. All rights reserved 4-46
Visibility Modifiers
In Java, we accomplish encapsulation through the
appropriate use of visibility modifiers
A modifier is a Java reserved word that specifies
particular characteristics of a method or data
We've used the final modifier to define constants
Java has three visibility modifiers:
public protected private
2004 Pearson Addison-Wesley. All rights reserved 4-47
Visibility Modifiers
public private
Variables
Methods
Provide services
to clients
Support other
methods in the
class
Enforce
encapsulation
Violate
encapsulation
2004 Pearson Addison-Wesley. All rights reserved 4-48
Accessors and Mutators
Because instance data is private, a class usually
provides services to access and modify data values
An accessor method returns the value of a variable
A mutator method changes the value of a variable
The names of accessor and mutator methods take
the form getX and setX, respectively, where X is the
name of the value
They are sometimes called getters and setters
2004 Pearson Addison-Wesley. All rights reserved 4-49
Mutator Restrictions
The use of mutators gives the class designer the
ability to restrict a clients options to modify an
objects state
A mutator is often designed so that the values of
variables can be set only within particular limits
For example, the setFaceValue mutator of the
Die class should have restricted the value to the
valid range (1 to MAX)
The private modifier restricts access to within a class, the default
modifier restricts access to within a package, and the public
modifier enables unrestricted access.

public class C1 {
public int x;
int y;
private int z;

public void m1() {
}
void m2() {
}
private void m3() {
}
}
public class C2 {
void aMethod() {
C1 o = new C1();
? o.x;
? o.y;
? o.z;

? o.m1();
? o.m2();
? o.m3();
}
}
package p1;
package p2;
public class C3 {
void aMethod() {
C1 o = new C1();
? o.x;
? o.y;
? o.z;

? o.m1();
? o.m2();
? o.m3();
}
}

class C1 {
...
}
public class C2 {
? C1
}
package p1;
package p2;
public class C3 {
? C1;
? C2;
}
The private modifier restricts access to within a class, the default
modifier restricts access to within a package, and the public
modifier enables unrestricted access.

public class C1 {
public int x;
int y;
private int z;

public void m1() {
}
void m2() {
}
private void m3() {
}
}
public class C2 {
void aMethod() {
C1 o = new C1();
can access o.x;
can access o.y;
cannot access o.z;

can invoke o.m1();
can invoke o.m2();
cannot invoke o.m3();
}
}
package p1;
package p2;
public class C3 {
void aMethod() {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;

can invoke o.m1();
cannot invoke o.m2();
cannot invoke o.m3();
}
}

class C1 {
...
}
public class C2 {
can access C1
}
package p1;
package p2;
public class C3 {
cannot access C1;
can access C2;
}
NOTE
An object cannot access its private members, as shown in
(b). It is OK, however, if the object is declared in its own
class, as shown in (a).

public class Foo {
private boolean x;

public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.x);
System.out.println(foo.convert());
}

private int convert(boolean b) {
return x ? 1 : -1;
}
}



(a) This is OK because object foo is used inside the Foo class
public class Test {
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.x);
System.out.println(foo.convert(foo.x));
}
}


(b) This is wrong because x and convert are private in Foo.

Example
public class Student {
private int id;
private BirthDate birthDate;

public Student(int ssn,
int year, int month, int day) {
id = ssn;
birthDate = new BirthDate(year, month, day);
}

public int getId() {
return id;
}

public BirthDate getBirthDate() {
return birthDate;
}
}
public class BirthDate {
private int year;
private int month;
private int day;

public BirthDate(int newYear,
int newMonth, int newDay) {
year = newYear;
month = newMonth;
day = newDay;
}

public void setYear(int newYear) {
year = newYear;
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is changed!
}
}
2004 Pearson Addison-Wesley. All rights reserved 4-54
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
2004 Pearson Addison-Wesley. All rights reserved 4-55
Method Declarations
Lets now examine method declarations in more
detail
A method declaration specifies the code that will
be executed when the method is invoked (called)
When a method is invoked, the flow of control
jumps to the method and executes its code
When complete, the flow returns to the place
where the method was called and continues
The invocation may or may not return a value,
depending on how the method is defined
2004 Pearson Addison-Wesley. All rights reserved 4-56
myMethod();
myMethod compute



Method Control Flow
If the called method is in the same class, only the
method name is needed
2004 Pearson Addison-Wesley. All rights reserved 4-57
doIt


helpMe
helpMe();



obj.doIt();
main

Method Control Flow
The called method is often part of another class or
object
2004 Pearson Addison-Wesley. All rights reserved 4-58
Method Header
A method declaration begins with a method header
char calc (int num1, int num2, String message)
method
name
return
type
parameter list
The parameter list specifies the type
and name of each parameter

The name of a parameter in the method
declaration is called a formal parameter
2004 Pearson Addison-Wesley. All rights reserved 4-59
Method Body
The method header is followed by the method body
char calc (int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt (sum);

return result;
}
The return expression
must be consistent with
the return type
sum and result
are local data

They are created
each time the
method is called, and
are destroyed when
it finishes executing

2004 Pearson Addison-Wesley. All rights reserved 4-60
The return Statement
The return type of a method indicates the type of
value that the method sends back to the calling
location
A method that does not return a value has a void
return type
A return statement specifies the value that will be
returned
return expression;
Its expression must conform to the return type
2004 Pearson Addison-Wesley. All rights reserved 4-61
Parameters
When a method is called, the actual parameters in the
invocation are copied into the formal parameters in
the method header
char calc (int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt (sum);

return result;
}
ch = obj.calc (25, count, "Hello");
2004 Pearson Addison-Wesley. All rights reserved 4-62
Bank Account Example
Lets look at another example that demonstrates
the implementation details of classes and methods
Well represent a bank account by a class named
Account
Its state can include the account number, the
current balance, and the name of the owner
An accounts behaviors (or services) include
deposits and withdrawals, and adding interest
2004 Pearson Addison-Wesley. All rights reserved 4-63
Driver Programs
A driver program drives the use of other, more
interesting parts of a program
Driver programs are often used to test other parts
of the software
The Transactions class contains a main method
that drives the use of the Account class,
exercising its services
See Transaction.java
See Account.java

2004 Pearson Addison-Wesley. All rights reserved 4-64
public class Transaction {
public static void main (String[] args){
Account acct1 = new Account ("Ted
Murphy", 72354, 102.56);
Account acct2 = new Account ("Jane
Smith", 69713, 40.00);
Account acct3 = new Account ("Edward
Demsey", 93757, 759.32);

acct1.deposit (25.85);

double smithBalance = acct2.deposit
(500.00);
System.out.println ("Smith balance after
deposit: " +
smithBalance);

System.out.println ("Smith balance after
withdrawal: " +
acct2.withdraw (430.75, 1.50));

acct1.addInterest();
acct2.addInterest();
acct3.addInterest();

System.out.println ();
System.out.println (acct1);
System.out.println (acct2);
System.out.println (acct3);
}
}


import java.text.NumberFormat;

public class Account{
private final double RATE = 0.035; // interest rate of 3.5%
private long acctNumber;
private double balance;
private String name;
public Account (String owner, long account, double initial) {
name = owner;
acctNumber = account;
balance = initial; }
public double deposit (double amount) {
balance = balance + amount;

return balance; }

public double withdraw (double amount, double fee) {
balance = balance - amount - fee;

return balance; }

public double addInterest () {
balance += (balance * RATE);
return balance; }

public double getBalance () {
return balance; }

public String toString () {
NumberFormat fmt = NumberFormat.getCurrencyInstance();

return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
}
}

2004 Pearson Addison-Wesley. All rights reserved 4-65
Outpu:t:

Smith balance after deposit: 540.0
Smith balance after withdrawal: 107.75

72354 Ted Murphy MYR132.90
69713 Jane Smith MYR111.52
93757 Edward Demsey MYR785.90
2004 Pearson Addison-Wesley. All rights reserved 4-66
Bank Account Example
acct1
72354 acctNumber
102.56 balance
name
Ted Murphy
acct2
69713 acctNumber
40.00 balance
name
Jane Smith
2004 Pearson Addison-Wesley. All rights reserved 4-67
Bank Account Example
There are some improvements that can be made to
the Account class
Formal getters and setters could have been
defined for all data
The design of some methods could also be more
robust, such as verifying that the amount
parameter to the withdraw method is positive
2004 Pearson Addison-Wesley. All rights reserved 4-68
Constructors Revisited
Note that a constructor has no return type
specified in the method header, not even void
A common error is to put a return type on a
constructor, which makes it a regular method
that happens to have the same name as the class
The programmer does not have to define a
constructor for a class
Each class has a default constructor that accepts
no parameters
2004 Pearson Addison-Wesley. All rights reserved 4-69
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
2004 Pearson Addison-Wesley. All rights reserved 4-70
Graphical Objects
Some objects contain information that determines
how the object should be represented visually
We did this in Chapter 2 when we defined the
paint method of an applet
Let's look at some other examples of graphical
objects
2004 Pearson Addison-Wesley. All rights reserved 4-71
Smiling Face Example
The SmilingFace program draws a face by
defining the paintComponent method of a panel
See SmilingFace.java
See SmilingFacePanel.java
The main method of the SmilingFace class
instantiates a SmilingFacePanel and displays it
The SmilingFacePanel class is derived from the
JPanel class using inheritance (extends)

2004 Pearson Addison-Wesley. All rights reserved 4-72
Smiling Face Example
The SmilingFace panel is a JPanel
In the Constructor method we:
Set the background color
Set the preferred size
Set the font
The JPanel has a paintComponent method
This method automatically gets called to
draw the panel

2004 Pearson Addison-Wesley. All rights reserved 4-73
Smiling Face Example
Every Swing component has a paintComponent
method
The paintComponent method accepts a Graphics
object that represents the graphics context for the
panel
We define the paintComponent method to draw
the face with appropriate calls to the Graphics
methods
Note the difference between drawing on a panel
and adding other GUI components to a panel
2004 Pearson Addison-Wesley. All rights reserved 4-74
Smiling Face Example
We add to the definition of this method to also
draw the face and the words
The first line of this method will almost always be:
super.paintComponent (Graphics g);
The super refers to the parent class

2004 Pearson Addison-Wesley. All rights reserved 4-75
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
2004 Pearson Addison-Wesley. All rights reserved 4-76
Graphical User Interfaces
A Graphical User Interface (GUI) in Java is created
with at least three kinds of objects:
components
events
listeners
We've previously discussed components, which
are objects that represent screen elements
labels, buttons, text fields, menus, etc.
Some components are containers that hold and
organize other components
frames, panels, applets, dialog boxes
2004 Pearson Addison-Wesley. All rights reserved 4-77
Events
An event is an object that represents some activity
to which we may want to respond
For example, we may want our program to perform
some action when the following occurs:
the mouse is moved
the mouse is dragged
a mouse button is clicked
a graphical button is clicked
a keyboard key is pressed
a timer expires
Events often correspond to user actions, but not
always
2004 Pearson Addison-Wesley. All rights reserved 4-78
Events and Listeners
The Java standard class library contains several
classes that represent typical events
Components, such as a graphical button, generate
(or fire) an event when it occurs
A listener object "waits" for an event to occur and
responds accordingly
We can design listener objects to take whatever
actions are appropriate when an event occurs
2004 Pearson Addison-Wesley. All rights reserved 4-79
Events and Listeners
Component
A component object
may generate an event
Listener
A corresponding listener
object is designed to
respond to the event
Event
When the event occurs, the component calls
the appropriate method of the listener,
passing an object that describes the event
2004 Pearson Addison-Wesley. All rights reserved 4-80
GUI Development
Generally we use components and events that are
predefined by classes in the Java class library
Therefore, to create a Java program that uses a
GUI we must:
instantiate and set up the necessary components
implement listener classes for any events we care about
establish the relationship between listeners and
components that generate the corresponding events
2004 Pearson Addison-Wesley. All rights reserved 4-81
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
2004 Pearson Addison-Wesley. All rights reserved 4-82
Buttons
A push button is a component that allows the user
to initiate an action by pressing a graphical button
using the mouse
A push button is defined by the JButton class
It generates an action event
The PushCounter example displays a push button
that increments a counter each time it is pushed
2004 Pearson Addison-Wesley. All rights reserved 4-83
Push Counter Example
The components of the GUI are:

The button
The label to display the counter
The panel to organize the components
The main frame
2004 Pearson Addison-Wesley. All rights reserved 4-84
Push Counter Example
An interface is a list of methods that the
implementing class must define
The only method in the ActionListener interface
is the actionPerformed method
The Java class library contains interfaces for
many types of events (chapter 6)
The PushCounterPanel constructor:
instantiates the ButtonListener object
establishes relationship between button and listener
with the call to: addActionListener

2004 Pearson Addison-Wesley. All rights reserved 4-85
Push Counter Example
When the user presses the button:
The button component creates:
An ActionEvent object
Calls the actionPerformed method of the listener
This method increments the counter and resets
the text of the label
2004 Pearson Addison-Wesley. All rights reserved 4-86
Text Fields
Let's look at another GUI example that uses
another type of component
A text field allows the user to enter a line of input
If the cursor is in the text field, the text field
component generates an action event when the
enter key is pressed
2004 Pearson Addison-Wesley. All rights reserved 4-87
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class JFrame13 implements ActionListener {

private static void createAndShowGUI() {
JFrame13 app=new JFrame13();
// make frame..
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("I am a JFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(20,30,300,120);
frame.setLayout(null);
// make a panel
JPanel myPanel = new JPanel();
// make a text field
app.textField = new JTextField("Type here",20);
myPanel.add(app.textField);
// set up action listener
app.textField.addActionListener(app);
// make and add label
app.label = new JLabel("Result");
myPanel.add(app.label);
frame.setContentPane(myPanel);
frame.setVisible(true);
}

































public void actionPerformed(ActionEvent e)
{
// this happens when Enter hit on the text field
label.setText(textField.getText());
}


public static void main(String[] args) {
// start off..
try {
UIManager.setLookAndFeel(
"javax.swing.plaf.metal.MetalLookAndFeel" );
}
catch (Exception e)
{
System.out.println("Cant get laf");
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
// application object fields
JLabel label;
JTextField textField;
}

2004 Pearson Addison-Wesley. All rights reserved 4-88
Fahrenheit Example
Like the PushCounter example, the GUI is set up
in a separate panel class
The text field and labels are added to the panel
The panel is governed by the flow layout manager
The TempListener inner class defines the listener
for the action event generated by the text field
The FahrenheitPanel constructor instantiates
the listener and adds it to the text field
2004 Pearson Addison-Wesley. All rights reserved 4-89
Fahrenheit Example
When the user types a temperature and presses
enter, the text field generates the action event and
calls the actionPerformed method of the listener
The method retrieves the text using: getText()
This returns a character string and is converted to
an integer by using the parseInt() method
The actionPerformed method then computes the
conversion and updates the result label
The same listener object can listen to multiple
components
2004 Pearson Addison-Wesley. All rights reserved 4-90
Summary
Chapter 4 focused on:
class definitions
instance data
encapsulation and Java modifiers
method declaration and parameter passing
constructors
graphical objects
events and listeners
buttons and text fields

You might also like