Java Reference
In-Depth Information
394
S
ELF
C
HECK
1.
Suppose you want to use the
DataSet
class to find the
Country
object with the largest population. What condition must the
Country
class fulfill?
2.
Why can't the
add
method of the
DataSet
class have a parameter of
type
Object
?
C
OMMON
E
RROR
9.1: Forgetting to Define
Implementing Methods as Public
The methods in an interface are not declared as
public
, because they are public
by default. However, the methods in a class are not public by defaultȌtheir
default access level is Ȓpackageȓ access, which we discuss in
Chapter 10
. It is a
C
OMMON
E
RROR
to forget the
public
keyword when defining a method from an
interface:
public class BankAccount
implements Measurable
{
double getMeasure()
// Oops should be public
{
return balance;
}
. . .
}
Then the compiler complains that the method has a weaker access level, namely
package access instead of public access. The remedy is to declare the method as
public.
A
DVANCED
T
OPIC
9.1: Constants in Interfaces
Interfaces cannot have instance fields, but it is legal to specify constants. For
example, the
SwingConstants
interface defines various constants, such as
SwingConstants.NORTH
,
SwingConstants.EAST
, and so on.