SlideShare a Scribd company logo
Chapter 5:  Enhancing Classes  Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by Addison-Wesley Presentation slides are copyright 2002 by John Lewis, William Loftus, and Cara Cocking. All rights reserved. Instructors using the textbook may use and modify these slides for pedagogical purposes. *AP is a registered trademark of The College Entrance Examination Board which was not involved in the production of, and does not endorse, this product.
Enhancing Classes Now we can explore various aspects of classes and objects in more detail Chapter 5 focuses on: object references and aliases passing objects references as parameters the static modifier exceptions interfaces nested classes and inner classes dialog boxes GUI components, events, and listeners
References Recall from Chapter 2 that an object reference variable holds the memory address of an object Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object ChessPiece bishop1 = new ChessPiece(); bishop1
The null Reference An object reference variable that does not currently point to an object is called a  null reference The reserved word  null  can be used to explicitly set a null reference: name = null; or to check to see if a reference is currently null: if (name == null)   System.out.println ("Invalid");
The null Reference An object reference variable declared at the class level (an instance variable) is automatically initialized to null The programmer must carefully ensure that an object reference variable refers to a valid object before it is used Attempting to follow a null reference causes a  NullPointerException   to be thrown Usually a compiler will check to see if a local variable is being used without being initialized
The this Reference The  this  reference allows an object to refer to itself That is, the  this  reference, used inside a method, refers to the object through which the method is being executed Suppose the  this  reference is used in a method called  tryMe If  tryMe  is invoked as follows, the  this  reference refers to  obj1 : obj1.tryMe(); But in this case, the  this  reference refers to  obj2 : obj2.tryMe();
Assignment Revisited 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
Reference Assignment For object references, assignment copies the memory location: bishop2 = bishop1; Before bishop1 bishop2 After bishop1 bishop2
Aliases Two or more references that refer to the same object are called  aliases  of each other One object (and its data) can be accessed using different reference variables Aliases can be useful, but should be managed carefully Changing the object’s state (its variables) through one reference changes it for all of its aliases
Testing Objects for Equality The  ==  operator compares object references for equality, returning  true  if the references are aliases of each other bishop1 == bishop2 A method called  equals  is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the  ==  operator bishop1.equals(bishop2) We can redefine the  equals  method to return  true  under whatever conditions we think are appropriate
Objects as Parameters Parameters in a Java method are  passed by value This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) Passing parameters is therefore similar to an assignment statement When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other
Passing Objects to Methods What you do with a parameter inside a method may or may not have a permanent effect (outside the method) See  ParameterPassing .java  (page 253) See  ParameterTester .java  (page 254) See  Num.java  (page 255) Note the difference between changing the reference and changing the object that the reference points to
The static Modifier In Chapter 2 we discussed static methods (also called class methods) that can be invoked through the class name rather than through a particular object For example, the methods of the  Math  class are static: Math.sqrt (25) To write a static method, we apply the  static  modifier to the method definition The  static  modifier can be applied to variables as well It associates a variable or method with the class rather than with an object
Static Variables Static variables are also called  class variables   Normally, each object has its own data space, but if a variable is declared as static, only one copy of the variable exists private static float price; Memory space for a static variable is created when the class in which it is declared is loaded All objects created from the class share static variables The most common use of static variables is for constants
Static Methods Because it is static, the method can be invoked as: value = Helper.triple (5); public static int triple (int num) { int result; result = num * 3; return result; } class Helper
Static Methods The order of the modifiers can be interchanged, but by convention visibility modifiers come first  Recall that the  main  method is static;  it is invoked by the system without creating an object Static methods cannot reference instance variables, because instance variables don't exist until an object exists However, a static method can reference static variables or local variables
The static Modifier Static methods and static variables often work together See  CountInstances .java   (page 259) See  Slogan.java   (page 260)
Exceptions An  exception  is an object that describes an unusual or erroneous situation Exceptions are  thrown  by a program, and may be  caught  and  handled  by another part of the program A program can be separated into a normal execution flow and an  exception execution flow An  error  is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught
Exception Handling Java has a predefined set of exceptions and errors that can occur during execution A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it an another place in the program
Exception Handling If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message The message includes a  call stack trace  that indicates the line on which the exception occurred The call stack trace also shows the method call trail that lead to the attempted execution of the offending line See  Zero.java   (page 262)
The throw Statement Exceptions are thrown using the  throw  statement Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be thrown The following statement throws a  NoSuchElementException : throw new NoSuchElementException();
Interfaces A Java  interface  is a collection of abstract methods and constants An  abstract method  is a method header without a method body An abstract method can be declared using the modifier  abstract , but because all methods in an interface are abstract, usually it is left off An interface is used to establish, as a formal contract, a set of methods that a class will implement
Interfaces public interface Doable { public void doThis(); public int doThat(); public void doThis2 (double value, char ch); public boolean doTheOther (int num); } None of the methods in an interface are given a definition (body) interface is a reserved word A semicolon immediately follows each method header
Interfaces An interface cannot be instantiated Methods in an interface have public visibility by default A class formally implements an interface by stating so in the class header providing implementations for each abstract method in the interface If a class asserts that it implements an interface, it must define all methods in the interface
Interfaces public class CanDo implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } implements is a reserved word Each method listed in Doable is given a definition
Interfaces A class that implements an interface can implement other methods as well See  Complexity.java  (page 264) See  Question.java  (page 265) See  MiniQuiz .java  (page 266) In addition to (or instead of) abstract methods, an interface can contain constants When a class implements an interface, it gains access to all its constants
Interfaces A class can implement multiple interfaces The interfaces are listed in the implements clause The class must implement all methods in all interfaces listed in the header class ManyThings implements interface1, interface2 { // all methods of both interfaces }
Interfaces The Java standard class library contains many helpful interfaces The  Comparable  interface contains an abstract method called  compareTo , which is used to compare two objects The  String  class implements  Comparable , giving us the ability to put strings in lexicographic order The  List  interface is implemented by classes that represent an ordered collection of elements. The  Iterator  interface contains methods that allow the user to move easily through a collection of objects
The Comparable Interface The  Comparable  interface provides a common mechanism for comparing one object to another if (obj1.compareTo(obj2) < 0) System.out.println (“obj1 is less than obj2”); The result is negative is  obj1  is less that  obj2 , 0 if they are equal, and positive if  obj1  is greater than  obj2 When a programmer writes a class that implements the  Comparable  interface, it should follow this intent It's up to the programmer to determine what makes one object less than another
The List Interface The  List  interface represents an ordered collection of elements The  size  method returns the number of elements in the list The  add  method adds an element to the list The  iterator  and  listIterator  methods return iterators of the elements in the list
Iterator and ListIterator Interfaces The  Iterator  and  ListIterator  interfaces provide a means of moving through a collection of objects, one at a time The  hasNext  method returns a boolean result (true if there are items left to process) The  next  method returns the next object in the iteration The  remove  method removes the object most recently returned by the  next  method The  ListIterator  interface has additional methods ( add  and  set ) that insert or replace an element in the list
Designing Classes When designing a class, there are two pieces of information to think about: State (how an object is represented) Behavior (what an object does) The state becomes the instance variables of an object The behavior becomes the methods When thinking about behavior, you should think about how others might want to use the object
Nested Classes In addition to containing data and methods, a class can contain other classes A class declared within another class is called a  nested class Enclosing Class Nested Class
Nested Classes A nested class has access to the variables and methods of the enclosing class, even if they are declared private In certain situations this makes the implementation of the classes easier because they can share information easily Furthermore, the nested class can be protected by the enclosing class from external use This is a special relationship and should be used with care
Nested Classes A nested class produces a separate bytecode file If a nested class called  Inside  is declared in an outer class called  Outside , two bytecode files are produced: Outside.class Outside$Inside.class Nested classes can be declared as static, in which case they cannot refer to instance variables or methods
Inner Classes A nonstatic nested class is called an  inner class An inner class is associated with each instance of the enclosing class An instance of an inner class can exist only within an instance of an enclosing class
Dialog Boxes A  dialog box  is a graphical window that pops up on top of any currently active window for the user The Swing API contains a class called  JOptionPane  that simplifies the creation and use of basic dialog boxes There are three categories of  JOptionPane  dialog boxes A  message dialog  displays an output string An  input dialog  presents a prompt and a single input text field A  confirm dialog  presents the user with a simple yes-or-no question See  EvenOdd.java  (page 278)
The EvenOdd Program
Graphical User Interfaces A Graphical User Interface (GUI) is created with at least three kinds of objects components events listeners A GUI  component  defines a screen element to display information or allow the user to interact with the program buttons, text fields, labels, menus, etc. A  container  is a special component that holds and organizes other components dialog boxes, applets, frames, panels, etc.
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 a mouse button is clicked the mouse is dragged a graphical button is clicked a keyboard key is pressed a timer expires Events often correspond to user actions, but not always
Events and Listeners The Java standard class library contains several classes that represent typical events Components, such as an applet or a graphical button, generate (fire) an event when it occurs Other objects, called  listeners , wait for events to occur We can write listener objects to do whatever we want when an event occurs A listener object is often defined using an inner class
Events and Listeners When an event occurs, the generator calls the appropriate method of the listener, passing an object that describes the event Component This object may generate an event Listener This object waits for and responds to an event Event
Listener Interfaces We can create a listener object by writing a class that implements a particular  listener interface The Java standard class library contains several interfaces that correspond to particular event categories For example, the  MouseListener  interface contains methods that correspond to mouse events After creating the listener, we  add  the listener to the component that might generate the event to set up a formal relationship between the generator and listener
Creating GUIs To create a program with a GUI: define and set up the components create listener objects set up the relationships between the listeners and the components which generate events of interest define what happens in response to each event A  push button  is a component that allows the user to initiate an action with the press of the mouse button defined by the  JButton  class generates an  action event A  label  is a component that displays a line of text (or an image, or both) defined by the  JLabel  class
Creating GUIs The  init  method of an applet can be used to set up the GUI and add each component to the applet container  The Swing version of the  Applet  class is called  JApplet In a  JApplet , components are added to the applet's  content pane The content pane is retrieved using the  getContentPane  method A  JButton  generates an  action event See  PushCounter .java  (page 281)
The PushCounter Program
Action Listeners The interface corresponding to an action event is called  ActionListener , which defines only one method, called  actionPerformed The  ButtonListener  inner class implements the  ActionListener  interface in the  PushButton  program When the button is pushed, the  JButton  object invokes the  actionPerformed  method, passing it an  ActionEvent The listener method may or may not make use of the event object passed to it
GUI Applications A  frame  is a container component used for stand-alone GUI-based applications A  panel  is a container, but unlike a frame, it cannot be displayed on its own it must be added to another container it helps organize the components in a GUI See  Fahrenheit.java  (page 285) See  FahrenheitGUI .java  (page 286)
The Fahrenheit Program
Summary Chapter 5 has focused on: object references and aliases passing objects references as parameters the static modifier exceptions interfaces nested classes and inner classes dialog boxes GUI components, events, and listeners

More Related Content

PPT
Ap Power Point Chpt2
PPT
Ap Power Point Chpt7
PPT
Ap Power Point Chpt3 B
PPT
Ap Power Point Chpt4
PPT
Ap Power Point Chpt8
PPT
Ap Power Point Chpt3
PPT
Ap Power Point Chpt6
PPTX
OCA Java SE 8 Exam Chapter 2 Operators & Statements
Ap Power Point Chpt2
Ap Power Point Chpt7
Ap Power Point Chpt3 B
Ap Power Point Chpt4
Ap Power Point Chpt8
Ap Power Point Chpt3
Ap Power Point Chpt6
OCA Java SE 8 Exam Chapter 2 Operators & Statements

What's hot (20)

PPTX
Effective Java - Chapter 3: Methods Common to All Objects
PDF
Generics
PPT
C0 review core java1
PPT
Chapter 8 - Exceptions and Assertions Edit summary
PDF
Operators in java
PPTX
Fundamental programming structures in java
PPTX
Operators in java
PPT
Effective Java - Methods Common to All Objects
PPTX
Java Generics
DOCX
Java Interview Questions For Freshers
PPT
Chapter 9 - Characters and Strings
PPT
M C6java2
PPTX
OCA Java SE 8 Exam Chapter 3 Core Java APIs
PPTX
Operators in java
PPTX
Generic Programming in java
DOC
My c++
PPT
Jdk1.5 Features
PPTX
Evolution of c# - by K.Jegan
PPSX
Comparable and comparator – a detailed discussion
PDF
A COMPLETE FILE FOR C++
Effective Java - Chapter 3: Methods Common to All Objects
Generics
C0 review core java1
Chapter 8 - Exceptions and Assertions Edit summary
Operators in java
Fundamental programming structures in java
Operators in java
Effective Java - Methods Common to All Objects
Java Generics
Java Interview Questions For Freshers
Chapter 9 - Characters and Strings
M C6java2
OCA Java SE 8 Exam Chapter 3 Core Java APIs
Operators in java
Generic Programming in java
My c++
Jdk1.5 Features
Evolution of c# - by K.Jegan
Comparable and comparator – a detailed discussion
A COMPLETE FILE FOR C++
Ad

Viewers also liked (7)

PPT
JavaYDL20
PPT
Ap Power Point Chpt9
PPS
First Principles Of Cs Instruction
PPT
Lecture 4 recursion
PDF
Recursion Lecture in Java
PPT
Ap Power Point Chpt1
PPTX
Internet principles of operation
JavaYDL20
Ap Power Point Chpt9
First Principles Of Cs Instruction
Lecture 4 recursion
Recursion Lecture in Java
Ap Power Point Chpt1
Internet principles of operation
Ad

Similar to Ap Power Point Chpt5 (20)

PPTX
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
PPTX
Chapter 5:Understanding Variable Scope and Class Construction
PPT
Cso gaddis java_chapter9ppt
PPTX
Chapter 8 java
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
PPT
Object and class in java
PPT
Md03 - part3
PDF
principles of proramming language in cppg
PDF
C sharp chap5
PPTX
Java basics
PPTX
Upstate CSCI 200 Java Chapter 7 - OOP
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
PPTX
Class and Object.pptx from nit patna ece department
PPT
Core Java Concepts
PPT
PPT
Lecture 2 classes i
PPT
Java Basics
PDF
java-06inheritance
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Chapter 5:Understanding Variable Scope and Class Construction
Cso gaddis java_chapter9ppt
Chapter 8 java
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Object and class in java
Md03 - part3
principles of proramming language in cppg
C sharp chap5
Java basics
Upstate CSCI 200 Java Chapter 7 - OOP
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object.pptx from nit patna ece department
Core Java Concepts
Lecture 2 classes i
Java Basics
java-06inheritance

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Spectroscopy.pptx food analysis technology
PPT
Teaching material agriculture food technology
PDF
Electronic commerce courselecture one. Pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
1. Introduction to Computer Programming.pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Tartificialntelligence_presentation.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
MIND Revenue Release Quarter 2 2025 Press Release
cuic standard and advanced reporting.pdf
NewMind AI Weekly Chronicles - August'25-Week II
Spectroscopy.pptx food analysis technology
Teaching material agriculture food technology
Electronic commerce courselecture one. Pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
1. Introduction to Computer Programming.pptx
Group 1 Presentation -Planning and Decision Making .pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Spectral efficient network and resource selection model in 5G networks
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Network Security Unit 5.pdf for BCA BBA.
A comparative analysis of optical character recognition models for extracting...
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Mobile App Security Testing_ A Comprehensive Guide.pdf
Unlocking AI with Model Context Protocol (MCP)
Tartificialntelligence_presentation.pptx
Digital-Transformation-Roadmap-for-Companies.pptx

Ap Power Point Chpt5

  • 1. Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by Addison-Wesley Presentation slides are copyright 2002 by John Lewis, William Loftus, and Cara Cocking. All rights reserved. Instructors using the textbook may use and modify these slides for pedagogical purposes. *AP is a registered trademark of The College Entrance Examination Board which was not involved in the production of, and does not endorse, this product.
  • 2. Enhancing Classes Now we can explore various aspects of classes and objects in more detail Chapter 5 focuses on: object references and aliases passing objects references as parameters the static modifier exceptions interfaces nested classes and inner classes dialog boxes GUI components, events, and listeners
  • 3. References Recall from Chapter 2 that an object reference variable holds the memory address of an object Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object ChessPiece bishop1 = new ChessPiece(); bishop1
  • 4. The null Reference An object reference variable that does not currently point to an object is called a null reference The reserved word null can be used to explicitly set a null reference: name = null; or to check to see if a reference is currently null: if (name == null) System.out.println (&quot;Invalid&quot;);
  • 5. The null Reference An object reference variable declared at the class level (an instance variable) is automatically initialized to null The programmer must carefully ensure that an object reference variable refers to a valid object before it is used Attempting to follow a null reference causes a NullPointerException to be thrown Usually a compiler will check to see if a local variable is being used without being initialized
  • 6. The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through which the method is being executed Suppose the this reference is used in a method called tryMe If tryMe is invoked as follows, the this reference refers to obj1 : obj1.tryMe(); But in this case, the this reference refers to obj2 : obj2.tryMe();
  • 7. Assignment Revisited 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
  • 8. Reference Assignment For object references, assignment copies the memory location: bishop2 = bishop1; Before bishop1 bishop2 After bishop1 bishop2
  • 9. Aliases Two or more references that refer to the same object are called aliases of each other One object (and its data) can be accessed using different reference variables Aliases can be useful, but should be managed carefully Changing the object’s state (its variables) through one reference changes it for all of its aliases
  • 10. Testing Objects for Equality The == operator compares object references for equality, returning true if the references are aliases of each other bishop1 == bishop2 A method called equals is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator bishop1.equals(bishop2) We can redefine the equals method to return true under whatever conditions we think are appropriate
  • 11. Objects as Parameters Parameters in a Java method are passed by value This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) Passing parameters is therefore similar to an assignment statement When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other
  • 12. Passing Objects to Methods What you do with a parameter inside a method may or may not have a permanent effect (outside the method) See ParameterPassing .java (page 253) See ParameterTester .java (page 254) See Num.java (page 255) Note the difference between changing the reference and changing the object that the reference points to
  • 13. The static Modifier In Chapter 2 we discussed static methods (also called class methods) that can be invoked through the class name rather than through a particular object For example, the methods of the Math class are static: Math.sqrt (25) To write a static method, we apply the static modifier to the method definition The static modifier can be applied to variables as well It associates a variable or method with the class rather than with an object
  • 14. Static Variables Static variables are also called class variables Normally, each object has its own data space, but if a variable is declared as static, only one copy of the variable exists private static float price; Memory space for a static variable is created when the class in which it is declared is loaded All objects created from the class share static variables The most common use of static variables is for constants
  • 15. Static Methods Because it is static, the method can be invoked as: value = Helper.triple (5); public static int triple (int num) { int result; result = num * 3; return result; } class Helper
  • 16. Static Methods The order of the modifiers can be interchanged, but by convention visibility modifiers come first Recall that the main method is static; it is invoked by the system without creating an object Static methods cannot reference instance variables, because instance variables don't exist until an object exists However, a static method can reference static variables or local variables
  • 17. The static Modifier Static methods and static variables often work together See CountInstances .java (page 259) See Slogan.java (page 260)
  • 18. Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled by another part of the program A program can be separated into a normal execution flow and an exception execution flow An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught
  • 19. Exception Handling Java has a predefined set of exceptions and errors that can occur during execution A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it an another place in the program
  • 20. Exception Handling If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message The message includes a call stack trace that indicates the line on which the exception occurred The call stack trace also shows the method call trail that lead to the attempted execution of the offending line See Zero.java (page 262)
  • 21. The throw Statement Exceptions are thrown using the throw statement Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be thrown The following statement throws a NoSuchElementException : throw new NoSuchElementException();
  • 22. Interfaces A Java interface is a collection of abstract methods and constants An abstract method is a method header without a method body An abstract method can be declared using the modifier abstract , but because all methods in an interface are abstract, usually it is left off An interface is used to establish, as a formal contract, a set of methods that a class will implement
  • 23. Interfaces public interface Doable { public void doThis(); public int doThat(); public void doThis2 (double value, char ch); public boolean doTheOther (int num); } None of the methods in an interface are given a definition (body) interface is a reserved word A semicolon immediately follows each method header
  • 24. Interfaces An interface cannot be instantiated Methods in an interface have public visibility by default A class formally implements an interface by stating so in the class header providing implementations for each abstract method in the interface If a class asserts that it implements an interface, it must define all methods in the interface
  • 25. Interfaces public class CanDo implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } implements is a reserved word Each method listed in Doable is given a definition
  • 26. Interfaces A class that implements an interface can implement other methods as well See Complexity.java (page 264) See Question.java (page 265) See MiniQuiz .java (page 266) In addition to (or instead of) abstract methods, an interface can contain constants When a class implements an interface, it gains access to all its constants
  • 27. Interfaces A class can implement multiple interfaces The interfaces are listed in the implements clause The class must implement all methods in all interfaces listed in the header class ManyThings implements interface1, interface2 { // all methods of both interfaces }
  • 28. Interfaces The Java standard class library contains many helpful interfaces The Comparable interface contains an abstract method called compareTo , which is used to compare two objects The String class implements Comparable , giving us the ability to put strings in lexicographic order The List interface is implemented by classes that represent an ordered collection of elements. The Iterator interface contains methods that allow the user to move easily through a collection of objects
  • 29. The Comparable Interface The Comparable interface provides a common mechanism for comparing one object to another if (obj1.compareTo(obj2) < 0) System.out.println (“obj1 is less than obj2”); The result is negative is obj1 is less that obj2 , 0 if they are equal, and positive if obj1 is greater than obj2 When a programmer writes a class that implements the Comparable interface, it should follow this intent It's up to the programmer to determine what makes one object less than another
  • 30. The List Interface The List interface represents an ordered collection of elements The size method returns the number of elements in the list The add method adds an element to the list The iterator and listIterator methods return iterators of the elements in the list
  • 31. Iterator and ListIterator Interfaces The Iterator and ListIterator interfaces provide a means of moving through a collection of objects, one at a time The hasNext method returns a boolean result (true if there are items left to process) The next method returns the next object in the iteration The remove method removes the object most recently returned by the next method The ListIterator interface has additional methods ( add and set ) that insert or replace an element in the list
  • 32. Designing Classes When designing a class, there are two pieces of information to think about: State (how an object is represented) Behavior (what an object does) The state becomes the instance variables of an object The behavior becomes the methods When thinking about behavior, you should think about how others might want to use the object
  • 33. Nested Classes In addition to containing data and methods, a class can contain other classes A class declared within another class is called a nested class Enclosing Class Nested Class
  • 34. Nested Classes A nested class has access to the variables and methods of the enclosing class, even if they are declared private In certain situations this makes the implementation of the classes easier because they can share information easily Furthermore, the nested class can be protected by the enclosing class from external use This is a special relationship and should be used with care
  • 35. Nested Classes A nested class produces a separate bytecode file If a nested class called Inside is declared in an outer class called Outside , two bytecode files are produced: Outside.class Outside$Inside.class Nested classes can be declared as static, in which case they cannot refer to instance variables or methods
  • 36. Inner Classes A nonstatic nested class is called an inner class An inner class is associated with each instance of the enclosing class An instance of an inner class can exist only within an instance of an enclosing class
  • 37. Dialog Boxes A dialog box is a graphical window that pops up on top of any currently active window for the user The Swing API contains a class called JOptionPane that simplifies the creation and use of basic dialog boxes There are three categories of JOptionPane dialog boxes A message dialog displays an output string An input dialog presents a prompt and a single input text field A confirm dialog presents the user with a simple yes-or-no question See EvenOdd.java (page 278)
  • 39. Graphical User Interfaces A Graphical User Interface (GUI) is created with at least three kinds of objects components events listeners A GUI component defines a screen element to display information or allow the user to interact with the program buttons, text fields, labels, menus, etc. A container is a special component that holds and organizes other components dialog boxes, applets, frames, panels, etc.
  • 40. 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 a mouse button is clicked the mouse is dragged a graphical button is clicked a keyboard key is pressed a timer expires Events often correspond to user actions, but not always
  • 41. Events and Listeners The Java standard class library contains several classes that represent typical events Components, such as an applet or a graphical button, generate (fire) an event when it occurs Other objects, called listeners , wait for events to occur We can write listener objects to do whatever we want when an event occurs A listener object is often defined using an inner class
  • 42. Events and Listeners When an event occurs, the generator calls the appropriate method of the listener, passing an object that describes the event Component This object may generate an event Listener This object waits for and responds to an event Event
  • 43. Listener Interfaces We can create a listener object by writing a class that implements a particular listener interface The Java standard class library contains several interfaces that correspond to particular event categories For example, the MouseListener interface contains methods that correspond to mouse events After creating the listener, we add the listener to the component that might generate the event to set up a formal relationship between the generator and listener
  • 44. Creating GUIs To create a program with a GUI: define and set up the components create listener objects set up the relationships between the listeners and the components which generate events of interest define what happens in response to each event A push button is a component that allows the user to initiate an action with the press of the mouse button defined by the JButton class generates an action event A label is a component that displays a line of text (or an image, or both) defined by the JLabel class
  • 45. Creating GUIs The init method of an applet can be used to set up the GUI and add each component to the applet container The Swing version of the Applet class is called JApplet In a JApplet , components are added to the applet's content pane The content pane is retrieved using the getContentPane method A JButton generates an action event See PushCounter .java (page 281)
  • 47. Action Listeners The interface corresponding to an action event is called ActionListener , which defines only one method, called actionPerformed The ButtonListener inner class implements the ActionListener interface in the PushButton program When the button is pushed, the JButton object invokes the actionPerformed method, passing it an ActionEvent The listener method may or may not make use of the event object passed to it
  • 48. GUI Applications A frame is a container component used for stand-alone GUI-based applications A panel is a container, but unlike a frame, it cannot be displayed on its own it must be added to another container it helps organize the components in a GUI See Fahrenheit.java (page 285) See FahrenheitGUI .java (page 286)
  • 50. Summary Chapter 5 has focused on: object references and aliases passing objects references as parameters the static modifier exceptions interfaces nested classes and inner classes dialog boxes GUI components, events, and listeners