Java Reference
In-Depth Information
You can set a time represented in a Date object for the calendar by invoking
calendar.setTime(date) and retrieve the time by invoking calendar.getTime() .
setTime(date)
getTime()
13.9 Can you create a Calendar object using the Calendar class?
13.10
Check
Point
Which method in the Calendar class is abstract?
13.11
How do you create a Calendar object for the current time?
13.12
For a Calendar object c , how do you get its year, month, date, hour, minute, and
second?
13.5 Interfaces
An interface is a class-like construct that contains only constants and abstract methods.
Key
Point
In many ways an interface is similar to an abstract class, but its intent is to specify common
behavior for objects of related classes or unrelated classes. For example, using appropriate
interfaces, you can specify that the objects are comparable, edible, and/or cloneable.
To distinguish an interface from a class, Java uses the following syntax to define an interface:
VideoNote
The concept of interface
modifier interface InterfaceName {
/** Constant declarations */
/** Abstract method signatures */
}
Here is an example of an interface:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}
An interface is treated like a special class in Java. Each interface is compiled into a separate
bytecode file, just like a regular class. You can use an interface more or less the same way
you use an abstract class. For example, you can use an interface as a data type for a reference
variable, as the result of casting, and so on. As with an abstract class, you cannot create an
instance from an interface using the new operator.
You can use the Edible interface to specify whether an object is edible. This is accom-
plished by letting the class for the object implement this interface using the implements
keyword. For example, the classes Chicken and Fruit in Listing 13.7 (lines 20, 39) imple-
ment the Edible interface. The relationship between the class and the interface is known
as interface inheritance . Since interface inheritance and class inheritance are essentially the
same, we will simply refer to both as inheritance .
interface inheritance
L ISTING 13.7
TestEdible.java
1 public class TestEdible {
2 public static void main(String[] args) {
3 Object[] objects = { new Tiger(), new Chicken(), new Apple()};
4 for ( int i = 0 ; i < objects.length; i++) {
5 if (objects[i] instanceof Edible)
6 System.out.println(((Edible)objects[i]).howToEat());
7
8 if (objects[i] instanceof Animal) {
9 System.out.println(((Animal)objects[i]).sound());
10 }
11 }
12 }
13 }
 
 
 
Search WWH ::




Custom Search