Lecture 15 - Chapter 6 Part 2

Download Report

Transcript Lecture 15 - Chapter 6 Part 2

Chapter 6
Object-Oriented
Design
Part 2
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
 Remember: instance variables are unique to each object; but
the methods are shared!!
• Suppose the this reference is used in a method called
tryMe, which is invoked as follows:
obj1.tryMe();
obj2.tryMe();
• In the first invocation, the this reference refers to
obj1; in the second it refers to obj2
© 2004 Pearson Addison-Wesley. All rights reserved
2/20
The this reference
• The this reference can be used to distinguish the
instance variables of a class from corresponding
method parameters with the same names
• The constructor of the Account class (from
Chapter 4) could have been written as follows:
public Account (Sring name, long acctNumber,
double balance)
{
this.name = name;
this.acctNumber = acctNumber;
this.balance = balance;
}
Here this.name refers to the instance
variable for ‘this’ object… (don’t need
different formal parameter names)
© 2004 Pearson Addison-Wesley. All rights reserved
3/20
Outline
Software Development Activities
Identifying Classes and Objects
Static Variables and Methods
Class Relationships
Interfaces
Enumerated Types Revisited
Method Design
Testing
GUI Design and Layout
© 2004 Pearson Addison-Wesley. All rights reserved
4/20
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 a set of methods
that a class will implement.
• Note: the Java interface is itself NOT a class!
© 2004 Pearson Addison-Wesley. All rights reserved
5/20
Interfaces
interface is a reserved word
(note: ‘class’ is not used)
None of the methods in
an interface are given
a definition (body)
public interface Doable
{
public void doThis();
public int doThat();
public void doThis2 (float value, char ch);
public boolean doTheOther (int num);
}
These are all abstract methods
because they are declared within
an ‘interface.’ They could be
preceded with ‘abstract’ but
this is not necessary!
© 2004 Pearson Addison-Wesley. All rights reserved
A semicolon immediately
follows each method header
This ‘prevents’ there being
a body for the method.
6/20
Note:
• In defining ‘classes,’ we say:
public class whatever
• In defining an ‘interface,’ we say
public interface whatever (we do Not say ‘class.’)
© 2004 Pearson Addison-Wesley. All rights reserved
7/20
Interfaces
• An interface cannot be instantiated.
 Recall, it is NOT a class! (thus 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
© 2004 Pearson Addison-Wesley. All rights reserved
8/20
Interfaces
public class CanDo implements Doable
{
public void doThis ()
implements is a
{
reserved word
// whatever
}
public void doThat ()
{
// whatever
}
Each method listed
in Doable is
given a definition
// etc.
}
Note: this class ‘implements’ the interface. All abstract methods in the
interface must be defined here in the class that ‘implements’ the interface.
If all the methods are not defined, then this class is itself abstract and cannot
be instantiated.
© 2004 Pearson Addison-Wesley. All rights reserved
9/20
Interfaces
• A class that implements an interface can
implement other methods as well
• See Complexity.java (ahead)
• See Question.java (ahead)
• See MiniQuiz.java (ahead)
• 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
© 2004 Pearson Addison-Wesley. All rights reserved
10/20
//************************************************
// Complexity.java
Author: Lewis/Loftus
//
// Represents the interface for an object that can be assigned
// an explicit complexity.
//************************************************
public interface Complexity
{
public void setComplexity (int complexity);
public int getComplexity();
}
Note the semicolon after the abstract methods!
Note: public  interface…
This interface allows many classes to ‘implement’ it in different ways.
© 2004 Pearson Addison-Wesley. All rights reserved
11/20
// Question.java
Author: Lewis/Loftus // Represents a question (and its answer).
public class Question implements Complexity
{
private String question, answer;
private int complexityLevel;
// Constructor: Sets up the question with a default complexity.
public Question (String query, String result)
// Of course, we usually need a Constructor….
{
question = query;
answer = result;
complexityLevel = 1;
}
// Sets the complexity level for this question.
public void setComplexity (int level)
// Must have this one
{
complexityLevel = level;
}
// Returns the complexity level for this question.
public int getComplexity()
// Must have this one.
{
return complexityLevel;
}
// Returns the question.
public String getQuestion()
{
return question;
}
// Do NOT code like I have the next two methods. Only for space here!
// Returns the answer to this question.
public String getAnswer()
{
return answer;
}
// Returns true if the candidate answer matches the answer.
public boolean answerCorrect (String candidateAnswer)
{
return answer.equals(candidateAnswer);
}
// Returns this question (and its answer) as a string.
public String toString()
{
© 2004 Pearson Addison-Wesley. All rights reserved
12/20
return question + "\n" + answer;
// MiniQuiz.java
Author: Lewis/Loftus
// Demonstrates the use of a class that implements an interface.
import java.util.Scanner;
public class MiniQuiz
{
// Presents a short quiz.
public static void main (String[] args)
{
Question q1, q2;
// Creates two references to Question objects.
String possible;
Scanner scan = new Scanner (System.in);
q1 = new Question ("What is the capital of Jamaica?", "Kingston"); // Creates object, q1
q1.setComplexity (4);
// then sets the complexity to 4.
q2 = new Question ("Which is worse, ignorance or apathy?", “I don't know and I don't care");
q2.setComplexity (10);
// Creates a second object, q2, and its complexity.
System.out.print (q1.getQuestion());
System.out.println (" (Level: " + q1.getComplexity() + ")");
possible = scan.nextLine();
if (q1.answerCorrect(possible))
System.out.println ("Correct");
else
System.out.println ("No, the answer is " + q1.getAnswer());
System.out.println();
System.out.print (q2.getQuestion());
System.out.println (" (Level: " + q2.getComplexity() + ")");
possible = scan.nextLine();
© 2004 Pearson Addison-Wesley. All rights reserved
13/20
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
}
© 2004 Pearson Addison-Wesley. All rights reserved
14/20
Interfaces
• The Java standard class library contains many helpful
interfaces
• The Comparable interface contains one abstract method
called compareTo, which is used to compare two objects
public interface Comparable
{
public int compareTo (Object obj2 );
}
• We discussed the compareTo method of the String class
in Chapter 5
• The String class implements Comparable, giving us the
ability to put strings in lexicographic order
•  Note: If the Java API provides the interface (fine), WE
must provide the “implementation” of that interface. This
© 2004 Pearson Addison-Wesley. All rights reserved
15/20
means we can tailor it to whatever!
The Comparable Interface
• Any class can implement Comparable to provide a
mechanism for comparing objects of that type.
• Thus WE can decide exactly how we want to
determine how two “things” are to be compared!
if (obj1.compareTo(obj2) < 0)
System.out.println ("obj1 is less than obj2");
• The value returned from compareTo should be
negative is obj1 is less that obj2, 0 if they are
equal, and positive if obj1 is greater than obj2
• When a programmer designs a class that
implements the Comparable interface, it should
follow this intent
© 2004 Pearson Addison-Wesley. All rights reserved
16/20
Implementing the Comparable Interface
• It's up to the programmer to determine what
makes one object less than another
• If we are comparing two … Strings, (this is already
done for us in String), we decide ‘how’ to compare.
•  If we are comparing two, say, air filters on cars,
we may decide to compare by comparing the
volume of air that each allows through the filter…
•  The implementation of the method can be as
straightforward or as complex as needed for the
situation
© 2004 Pearson Addison-Wesley. All rights reserved
17/20
The Iterator Interface
• As we discussed in Chapter 5, an iterator is an
object that provides a means of processing a
collection of objects one at a time
•  An iterator is created formally by implementing
the Iterator interface, which contains three
methods
• 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
• So, if we implement the Iterator interface, WE must
© 2004 Pearson Addison-Wesley. All rights reserved
18/20
define HOW we implement the Iterator!
The Iterator Interface
• By implementing the Iterator interface, a class
formally establishes that objects of that type are
iterators (that is, whatever we are iterating thru…,
whether the ‘collection’ is a list of Strings, objects,
integers, etc.)
• The programmer, as stated, must decide how best
to implement the iterator functions
• Once established, the for-each version of the for
loop can be used to process the items in the
iterator (See last slides in 5.3 lecture slides)
© 2004 Pearson Addison-Wesley. All rights reserved
19/20
Interfaces
• You could write a class that implements certain
methods (such as compareTo) without formally
implementing the interface (Comparable)
• However, formally establishing the relationship
between a class and an interface allows Java to
deal with an object in certain ways
• Interfaces are a key aspect of object-oriented
design in Java
• We discuss this idea further in Chapter 9
© 2004 Pearson Addison-Wesley. All rights reserved
20/20