Objects and Classes --
description
Transcript of Objects and Classes --
1
Objects and Classes -- Now that some low-level programming concepts have
been established, we can examine objects in more detail
Chapter 4 focuses on: the concept of objects the use of classes to create objects using predefined classes defining methods and passing parameters defining classes visibility modifiers static variables and methods method overloading
2
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
3
Writing Classes
The programs we’ve written in previous examples have used classes defined in the Java standard class library
Now we will begin to design programs that rely on classes that we write ourselves
The class that contains the main method is just the starting point of a program
True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality
4
Objects An object has:
behaviors - what it can do (or be done to it) state - characteristics that describe its being
For example, a particular bank account has an account number has a current balance can be deposited into can be withdrawn from
Or, a circle could be stored as an object with variables describing its’ size, and a method that draws it on the screen or calculates its’ area.
5
Objects
An object has: state - descriptive characteristics behaviors - what it can do (or be done to
it)
For example, consider a coin that can be flipped so that it's face shows either "heads" or "tails”
The state of the coin is its current face (heads or tails) The behavior of the coin is that it can be flipped Note that the behavior of the coin might change its
state
6
Objects
Objects often (but not always) model real world objects and contain variable and methods to describe it.
An Object must have a unique identity to distinguish it from all other objects.
Even if two objects have the same state and variables, they would have to have different names in the program.
An object’s behavior often modifies its state. When a ball rolls, it changes location.
7
Objects
Two objects can have the same state. Two BMW’s could have the same motors, leather, color etc., but they would be completely different entities defined by their name. E.g.
My BMW, Jessie’s BMW, or Kyles’s BMW and John’s BMW2.
Objects do not have to be tangible objects. They can be integers or error messages or exceptions.
The methods that an object contains define its operations - what it can do and what can be done to it.
Everything an object can do, everything that describes it is defined by its class.
8
Classes
A class is a blueprint of an object
It is the model or pattern from which objects are created
For example, the String class is used to define String objects
Each String object contains specific characters (its state)
Each String object can perform services (behaviors) such as .toUpperCase
9
Classes
The String class was provided for us by the Java standard class library.
But we can also write our own classes that define specific objects that we need.
For example, suppose we wanted to write a program that simulates the flipping of a coin.
We could write a Student class to represent a students in program that keeps track of student data.
10
Classes
A class contains data declarations and method declarations
int x, y;char ch;
Data declarations- define its stateData declarations- define its state
Method declarations -Method declarations -Define its behaviorDefine its behavior
11
Classes
A class defines the methods and types of data associated with an object.
Creating an object from a class is called instantiation; an object is an instance of a particular class.
Once you have defined a class, you can define many different instances with different features
12
Instances of objects
An instance of an object is another word for an actual object, it is a concrete representation.
A class is a generic representation of an object.
The Customer class could describe many bank accounts, but toms_savings is a particular bank account with a particular balance
13
Objects
An instance and an object are the same thing, both are concrete representations of their class.
The new operator creates an object from a class:
Customer toms_savings = new Customer();
This declaration asserts that toms_savings is a variable that refers to an object created from the Customer class
14
Creating Objects - Instantiation
The new operator creates an instance of a class and reserves memory for it.
The newly created object is set up by a call to a constructor of the Customer class.
Whenever you use the new operator, a special method defined in the given class ( a constructor) is called.
15
Object References The declaration of the object reference variable
and the creation of the object can be separate activities:
Customer toms_savings; // declares the variable
// now has memory allocated for its data
toms_savings = new Customer (125.89);
16
Instantiation and References
int num = 115;
num is variable of type int that is initialized to 115. When used in the program, it is evaluated to the value 115.
Chess_Piece pawn = new Chess_Piece();
pawn, on the other hand, is a variable that refers to an object of the class Chess_Piece. The new operator calls the constructor of the Chess_Piece class.
Until the constructor is called with the new operator, no memory is set aside for the pawn object. Each object has its own memory space
17
ConstructorsIf we declare:
Boat carnival;carnival = new Boat();
In the first line, carnival is a reference to an object of the class Boat.
No memory is yet allotted to it. It is not yet instantiated.
References hold the address of the memory location where the object is stored.
Until the new operator is called and carnival is initialized, carnival does not refer to any data in memory.
18
Constructors
A constructor is a special method used to initialize or create an object.
It initializes the new object and its variables, i.e., allocates memory for it.
It must have the same name as the class.
It can have parameters, which are often used to initialize some variables in the object.
19
Constructors For example, the constructor for the Customer class
could take a parameter specifying its initial balance:
Customer toms_savings = new Customer (“Tom, 125.89);
The 125.89 is a value used to initialize a variable called balance defined in the Customer class. “Tom” will stored as the customer’s name.
In the Customer class, the Constructor method receives the 125.89 and Tom values sent to it from the statement in main:
20
class Customer:
{
private String name; private int balance; // data that describes a customer
public Customer( String name1, double NewBalance)
{
name1 = name; // constructor balance = NewBalance;
}Customer toms_savings = new Customer (“Tom, 125.89);
We call the constructor with the above code and it creates a new customer account with an initial balance of 125.89 and the name of “Tom”
21
class Customer{ private double Balance; // instance variables private name;
public Customer(String Name1,double NewBalance) { Balance = NewBalance; // constructor
name = name1;} ….
……..
public double returnBalance () // method to return balance { return Balance;
}} // close class
22
Constructors
A constructor:
Is a special method that is used to set up a newly created object.
Often sets the initial values of variables. Always has the same name as the class. Does not return a value. Has no return type, not even void.
The programmer does not have to define a constructor for a class. Java will define a generic constructor.
23
Creating Classes The syntax for defining a class is:
class class-name
{ //class declaration
declarations of variables
constructors // class body
methods
} The class declaration declares the name of the class
along with other attributes. The variables, constructors, and methods of a class
are generically called members of the class.
24
Classes The values given to data in a class define the state
of an object created from the class
Methods define the behaviors of the object
For our Die class, we might declare an integer that represents the current value showing on the face
One of the methods would “roll” the die by setting that value to a random number between one and six
25
Classes We’ll 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 (page 157) See Die.java (page 158)
26
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 retrieve the current face value at any time
27
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
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
29
Instance Data
We can depict the two Die objects from the RollingDice program as follows:
die1 5faceValue
die2 2faceValue
Each object maintains its own faceValue variable, and thus its own state
30
class Rectangle
class Rectangle
{
int length, width; // instance data
public Rectangle( )
{ // constructor length = 10; width = 12;
}
Java supports name overloading for constructors so that a class can have any number of constructors, all of which have the same name.
31
Overloaded Constructors Another constructor that could be defined by Rectangle:
public Rectangle(int Newlength, int Newwidth) { length = Newlength; width = Newwidth}
Both constructors share the same name, Rectangle, but they have different parameter lists.
The compiler determines which constructors to use based on the number and types of the parameters/
32
Overloading Constructors
An overloaded constructor provides multiple ways to set up a new object
See SnakeEyes.java (page 203) See Die.java (page 204)
33
Constructor When creating an object, choose the constructor
whose arguments best reflect how you want to set up the new object.
The compiler can determine which constructor to use. based on the number and type of the arguments that you pass into the constructor.
The instance variables in your class need to have data assigned to them. You should use the constructor to give them these values.
34
Outline
Anatomy of a Class
Anatomy of a Method
Encapsulation
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
35
Objects
Once an object exists, its methods can be invoked using the dot operator:
Customer toms_savings = new Customer (125.89);
toms_savings.deposit (35.00);
This invokes the deposit method in the toms_savings object. Place the dot right after the object reference name toms_savings.
Variables could be accessed also using the dot operator.
36
Classes and Objects
A class defines the data types for an object, but a class does not store data values.
Each object has its own unique data space.
The variables defined in a class are called instance variables because each instance of the class has its own variables.
All methods in a class have access to all instance variables of the class.
Methods are shared among all objects of a class.
37
References
An object reference holds the memory address of an object
Chess_Piece bishop1 = new Chess_Piece();
All interaction with an object occurs through a reference variable.
A reference variable holds the address in memory where its instance variables and methods are stored.
bishop1
38
Reference Assignment
For object references, the value of the memory location is copied so that bishop1 points to same location bishop1 does:
bishop2 = bishop1;Before
bishop1 bishop2
After
bishop1 bishop2
Lost!
39
Object Variables
When you create an object with :
Chesspiece bishop = new Chesspiece();
You are creating a “handle” which you can use to
obtain, or change the value of the object variable - bishop.
You can make bishop point to another location in memory.
40
Objects
Primitive variables like num don’t act this way. Two primitive variables can hold the same number but they refer to different locations in memory.
You can’t change a and b’s location in memory.
int a = 32; a b int b = 32;
You can also have two or more handles to the object bishop by creating aliases for it.
32 32
41
Assignment
The act of assignment takes a copy of a value and stores it in a variable
For primitive types:
num2 = num1;
Before
num1
5
num2
12
After
num1
5
num2
5
42
Aliases
Two or more references that refer to the same object are called aliases of each other. There is only one copy of the object (and its’ data), but with multiple ways to access it.
Each alias object contains the same memory address.
Aliases can be useful, but should be managed carefully
If you change the state of one object, you also the change the state of all its aliases, because they refer to the same object.
43
Garbage Collection
When an object is lost as in the previous example - it no longer has a object referring to it, it is cleaned up automatically by Java with garbage collection,
Therefore, when an object no longer has any valid references to it, it can no longer be accessed by the program.
It is useless, and therefore called garbage
Java performs automatic garbage collection periodically, returning an object's memory to the system for future use.
44
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 value
We've used the modifier final to define a constant
Java has three visibility modifiers: public, private, and protected
We will discuss the protected modifier more completely when we get to inheritance.
45
Visibility Modifiers
Members of a class that are declared with public visibility can be accessed from anywhere
Members of a class that are declared with private visibility can only be accessed from inside the class
Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package
Java modifiers are discussed in detail in Appendix F
46
Visibility Modifiers
As a general rule, no object's data should be declared with public visibility
Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients.
Public methods are also called service methods
A method created simply to assist a service method is called a support method.
Since a support method is not intended to be called by a client, it should not be declared with public visibility.
47
Visibility Modifiers
public private
Variables
Methods Provide servicesto clients
Support othermethods in the
class
Enforceencapsulation
Violateencapsulation
48
Protected The next access level specifier is protected, which allows
the class itself, subclasses and all classes in the same package to access the members.
Use the protected access level when it's appropriate for a class's subclasses to have access to the member classes.
This modifier is more important we study Inheritance.
The protected specifier affects access for classes in the same package?
49
Writing Methods
A method declaration specifies the code that will be executed when the method is invoked (or 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 was defined
50
myMethod();
myMethodcompute
Method Control Flow
The called method could be within the same class, in which case only the method name is needed
51
doIt
helpMe
helpMe();
obj.doIt();
main
Method Control Flow
The called method could be part of another class or object
Driver class Class used by driver class
52
Methods We have been using the main method and other
methods.
public int cube ( int number)
{ int cube; cube = number * number * number; return cube;} // method third_power
Method Declaration
Method Body
The method’s declaration defines all the method’s attributes, such as access level (public), return type (int), name (cube) and arguments (number);
53
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.
The return statement specifies the value that will be returned.
Its expression must conform to the return type.
54
Method Declarations A method declaration begins with a method header
char calc (int num1, int num2, String message)
methodmethodnamename
returnreturntypetype
parameter listparameter list
The parameter list specifies the typeThe parameter list specifies the typeand name of each parameterand name of each parameter
The name of a parameter in the methodThe name of a parameter in the methoddeclaration is called a declaration is called a formal argumentformal argument
55
Method Declarations 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 beThe return expression must beconsistent with the return typeconsistent with the return type
sum and resultsum and resultare are local datalocal data
They are created each They are created each time the method is called, time the method is called, and are destroyed when and are destroyed when it finishes executingit finishes executing
56
Methods
The method body is where all the action takes place. It contains the Java instructions that implement the method.
The method’s declaration provides a lot of information about the method. All methods follow the same syntax:
return-type method-name ( parameter-list ) { statement-list }
The return type may be any valid Java data type.(int, float..)
57
Calling Methods When you call a class method, you must first create an
object with which you will call it.
To call the method deposit in the Customer class, you would first create an object in your main method in the Bank class, e.g.
Customer TJ_Savings = new Customer(Name,Balance);
Then to call the deposit method, you would use:
TJ_Savings.deposit(500)
Which deposits 500 dollars into TJ’s account .
58
Methods
A method definition:
class MathMethods {
public int third_power (int number) { int cube; cube = number * number * number; return cube; } // method third_power} // close class
cube is a local variable. The action performed is to cube the parameter number. The value returned is the integer cube.
59
Methods
A method may contain local declarations as well as executable statements.
Variables declared locally can only be used locally. They have no value outside of the method.
The third_power method could be written without any local variables:
int third_power (int number) { return number * number * number; } // method third_power
60
Local Data As we’ve seen, local variables can be declared
inside a method
The formal parameters of a method create automatic local variables when the method is invoked
When the method finishes, all local variables are destroyed (including the formal parameters)
Keep in mind that instance variables, declared at the class level, exists as long as the object exists
61
Overloading Methods Method overloading is the process of using the same
method name for multiple methods. The signature of each overloaded method must be unique
The signature is based on the number, type, and order of the parameters.
The compiler must be able to determine which version of the method is being invoked by analyzing the parameters. Thus, one method must differ from another by the number and type of parameters it uses.
The return type of the method is not part of the signature
62
Overloading Methods
int tryMe (int x){ return x*x;}
Version 1Version 1
int tryMe (int x, float y){ return x*y;}
Version 2Version 2
result = tryMe (25, 4.32)
InvocationInvocation
63
Overloaded Methods
The println method is overloaded:
println (String s)
println (int i)
println (double d)
etc.
The following lines invoke different versions of the println method:
System.out.println ("The total is:");
System.out.println (total);
64
Overloaded Methods
Constructors are often overloaded to provide multiple ways to set up a new object.
public Customer (int account)
{
account_number = account;
balance = 0.0;
} // constructor Customer
public Customer (int account, double initial)
{
account_number = account;
balance = initial;
} // constructor Customer
65
Data Scope
The scope of data is the area in a program in which that data can be used (referenced). That is the area where it has a legal value.
Variables declared at the class level can be used by all methods in that class.
Data declared within a method can only be used in that method. It is considered local to that method.
Data declared within a method is called local data.
66
Accessors and Mutators
Because instance data is private, a class usually provides services to access and modify data values
An accessor method returns the current 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”
67
Mutator Restrictions The use of mutators gives the class designer the
ability to restrict a client’s options to modify an object’s 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)
We’ll see in Chapter 5 how such restrictions can be implemented
68
Parameters A method can be defined to accept zero or more
parameters.
When you write the method, you declare the number and type of parameters. Each parameter in the parameter list is specified by its type and name.
You can pass a parameter of any valid Java data type, including double, float, and integer, and reference types like arrays and classes.
You cannot pass methods.(except as part of an object.)
69
parameters
The parameters in the method definition are called formal parameters.
They receive their values from the actual parameters in the calling method.
The values passed to a method when it is invoked are called actual parameters.
If the main method calls a print method, main is the calling method. The method it calls is sent the actual parameters.
70
Parameters Each time a method is called, the actual arguments in
the invocation are copied into the formal arguments
public char calc (int num1, int num2, String message)
{ int sum = num1 + num2; char result = message.charAt (sum);
return result;}
public static void main(String[] args){ int num = 7; MathMethods obj = new MathMethods(); char ch = obj.calc (num, count, "Hello");}
71
Parameters
They receive their values from the actual parameters in the calling method.
The values passed to a method when it is invoked are called actual parameters.
When a parameter is passed, a copy of the value is made and assigned to the formal parameter. Arguments are Passed by Value.
When the method is invoked, it receives a copy of value of the variable passed in, not the original variable.
72
Both primitive types and object references can be passed as parameters.
When a primitive type is passed, pass by value means the method cannot change its value.
When the argument is an object reference , the formal parameter becomes an alias of the actual parameter.
It cannot change the reference of the object, but it can access the object’s methods and modify the accessible variables within the object.
Parameters
73
Parameters
You often do want a method to modify the value of variable you are sending it.
For a method to modify a variable, it must be a reference type, such as a class or an array. Objects and arrays are passed by value, but their value is an address in memory.
When an object is passed as an actual parameter, the formal parameter in the called method refers to same location in memory as the calling method.
The formal parameter is an alias of the actual parameter.
74
Main Method
No value is returned after the main is executed because at the end of the main method the program is finished.
The data type of the return value must match the method’s return type.
You can’t return a float if the return type is integer. Methods can also return objects.
The class of the returned object must be of the same class or a subclass of the return type.
75
The Coin Class
In our Coin class we could define the following data: face, an integer that represents the current face HEADS and TAILS, integer constants that
represent the two possible states
We might also define the following methods: a Coin constructor, to set up the object a flip method, to flip the coin a getFace method, to return the current face a toString method, to return a string description for printing
76
The Coin Class
See CountFlips.java (page 179) See Coin.java (page 180)
Once the Coin class has been defined, we can use it again in other programs as needed.
Note that the CountFlips program did not use the toString method.
A program will not necessarily use every service provided by an object
77
Instance Data The face variable in the Coin class is called instance
data because each instance (object) of the Coin class has its own.
A class declares the type of the data, but it does not reserve any memory space for it
Every time a Coin object is created, a new face variable is created as well.
The objects of a class share the method definitions, but they have unique data space.
That's the only way two objects can have different states.
78
Instance Data See FlipRace.java (page 182)
face 0
coin1
int face;
class Coin
face 1
coin2
79
Writing Classes
See BankAccounts.java (page 188) See Account.java (page 189)
An aggregate object is an object that contains references to other objects.
An Account object is an aggregate object because it contains a reference to a String object (that holds the owner's name).
An aggregate object represents a has-a relationship.
A bank account has a name
80
Bank Account Example Let’s look at another example that demonstrates the
implementation details of classes and methods
We’ll represent a bank account by a class named Account
It’s state can include the account number, the current balance, and the name of the owner
An account’s behaviors (or services) include deposits and withdrawals, and adding interest
81
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 Transactions.java (page 172) See Account.java (page 173)
82
Bank Account Example
acct1 72354acctNumber
102.56balance
name “Ted Murphy”
acct2 69713acctNumber
40.00balance
name “Jane Smith”
83
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
84
You can take one of two views of an object:
internal - the structure of its data, the algorithms used by its methods.
external - the interaction of the object with other objects in the program
From the external view, an object is an encapsulated entity, providing a set of specific services. You don’t have to know the details of how these services are implemented.
Objects
85
Objects
These services define the interface to the object.
They are provided by the programmer to offer other objects specific services.
In a Bank object, these services might include a withdraw method or deposit method.
Everything that an object knows (its state) and can do (its behavior) is expressed by the variables and methods within that object.
86
Encapsulation
A software object that models your bike has variables that indicate the bike’s current state:
Its speed is 10 mph, its pedal cadence is 90 rpm, its current gear is fifth.
The nucleus of an object is comprised of private variables and public methods.
Methods surround and hide the object's nucleus from other objects in the program.
87
Encapsulation
Packaging an object's variables within the protective custody of its methods is called encapsulation.
Encapsulation is used to hide unimportant implementation details from other objects.
When you want to drive a car, you don't need to know how the motor works.
88
Encapsulation
Similarly in software programs, you don't need to know how a class is implemented, you just need to know which methods to invoke.
Thus, the implementation details can change at any time without affecting other parts of the program.
89
Abstraction
Encapsulation is a powerful abstraction
An abstraction hides the right details at the right time
We use abstractions every day: driving a car using a computer
Encapsulation makes an object easy to manage mentally because its interaction with clients is limited to a set of well-defined services
90
Encapsulation Encapsulating related variables and
methods into an object bundle provides 2 major benefits:
Modularity --
The source code for an object can be written and maintained independently of the source code for other objects.
Also, an object can be easily passed around in the system.
91
Encapsulation
Information hiding ---
public interface that other objects can use to communicate with it.
But the object can maintain private information and methods that can be changed at any time without affecting the other objects that depend on it.
92
Encapsulation
An encapsulated object can be thought of as a black box
Its inner workings are hidden to the client, which only invokes the interface methods
ClientClient Methods
Data
93
Classes and Objects
Class Customer
Two Objects
int account_numberdouble balance
account_number
balance
2908371
573.21
account_number
balance
4113787
9211.84
94
Encapsulation
An object should be :
self-governing; any changes to the object's state (its variables) should be accomplished by that object's methods.
We should make it difficult, if not impossible, for another object to "reach in" and alter an object's state.
95
Encapsulation
The user, or client, of an object can request its services, but not be aware of how those services are accomplished.
An object has complete control over whether other objects can access its variables and methods and in fact, can specify which other objects have access.
96
Encapsulation
An encapsulated object can be thought of as a black box; its inner workings are hidden to the client
client
toms_savings deposit
withdraw
add_interest
produce_statement
97
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)
98
UML Class Diagrams
A UML class diagram for the RollingDice program:
RollingDice
main (args : String[]) : void
Die
faceValue : introll() : intsetFaceValue (int value) : voidgetFaceValue() : inttoString() : String
99
Classes
public By default, a class can be used only by other classes in the package. The public modifier declares it usable by all packages.
final Declares that the class cannot be subclassed
extends Super The extends clause identifies Super as the superclass of the class and inserts the class into the superclasses hierarchy.
Some class declarations and definitions:
100
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
101
Applet Methods
In previous examples we've used the paint method of the Applet class to draw on an applet
The Applet class has several methods that are invoked automatically at certain points in an applet's life
The init method, for instance, is executed only once when the applet is initially loaded
The Applet class also contains other methods that generally assist in applet processing
102
Graphical Objects Any object we define by writing a class can have
graphical elements
The object must simply obtain a graphics context (a Graphics object) in which to draw
An applet can pass its graphics context to another object just as it can any other parameter
See LineUp.java (page 212) See StickFigure.java (page 215)
103
Graphical Objects Some objects contain information that determines
how the object should be represented visually
Most GUI components are graphical objects
We can have some effect on how components get drawn
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
104
Smiling Face Example
The SmilingFace program draws a face by defining the paintComponent method of a panel
See SmilingFace.java (page 177)
See SmilingFacePanel.java (page 178)
The main method of the SmilingFace class instantiates a SmilingFacePanel and displays it
The SmilingFacePanel class is derived from the JPanel class using inheritance
105
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
106
Splat Example The Splat example is structured a bit differently
It draws a set of colored circles on a panel, but each circle is represented as a separate object that maintains its own graphical information
The paintComponent method of the panel "asks" each circle to draw itself
See Splat.java (page 180) See SplatPanel.java (page 181) See Circle.java (page 182)
107
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
108
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
109
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
110
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
111
Events and Listeners
Component
A component objectmay generate an event
Listener
A corresponding listenerobject is designed torespond to the event
Event
When the event occurs, the component callsthe appropriate method of the listener,
passing an object that describes the event
112
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
Let's now explore some new components and see how this all comes together
113
Outline
Anatomy of a Class
Encapsulation
Anatomy of a Method
Graphical Objects
Graphical User Interfaces
Buttons and Text Fields
114
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
See PushCounter.java (page 186) See PushCounterPanel.java (page 187)
115
Push Counter Example The components of the GUI are the button, a label to
display the counter, a panel to organize the components, and the main frame
The PushCounterPanel class is represents the panel used to display the button and label
The PushCounterPanel class is derived from JPanel using inheritance
The constructor of PushCounterPanel sets up the elements of the GUI and initializes the counter to zero
116
Push Counter Example The ButtonListener class is the listener for the
action event generated by the button
It is implemented as an inner class, which means it is defined within the body of another class
That facilitates the communication between the listener and the GUI components
Inner classes should only be used in situations where there is an intimate relationship between the two classes and the inner class is not needed in any other context
117
Push Counter Example Listener classes are written by implementing a
listener interface
The ButtonListener class implements the ActionListener interface
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
We discuss interfaces in more detail in Chapter 6
118
Push Counter Example
The PushCounterPanel constructor:
instantiates the ButtonListener object
establishes the relationship between the button and the listener by the call to addActionListener
When the user presses the button, the button component creates an ActionEvent object and calls the actionPerformed method of the listener
The actionPerformed method increments the counter and resets the text of the label
119
Text Fields Let's look at another GUI example that uses another
type of component
A text field allows the user to enter one 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
See Fahrenheit.java (page 190) See FahrenheitPanel.java (page 191)
120
Fahrenheit Example
Like the PushCounter example, the GUI is set up in a separate panel class
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
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 actionPerformed method computes the conversion and updates the result label