模板类型接口
NOTE: As of Java SE 5.0, the Comparable interface has been enhanced to be a generic type.
public interface Comparable<T>
{
int compareTo(T other); // parameter has type T
} For example, a class that implements Comparable<Employee> must supply a method int compareTo(Employee other)
You can still use the “raw” Comparable type without a type parameter, but then you have to manually cast the parameter of the compareTo method to the desired type. Allmethods of an interface are automatically public.Just as methods in an interface are automatically public, fields are always public static final.
inner class
内部类可以访问外部类的所有变量
outer class reference of an inner class
OuterClass.this 如 if (TalkingClock.this.beep) Toolkit.getDefaultToolkit().beep();you can write the inner object constructor more explicitly, using the syntax
outerObject .new InnerClass(construction parameters) 如 TalkingClock jabberer = new TalkingClock(1000, true); TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
Accessing final Variables from Outer Methods
Local classes have another advantage over other inner classes. Not only can they access the fields of their outer classes, they can even access local variables! However, those local variables must be declared final. Here is a typical example. Let’s move theinterval and beep parameters from the TalkingClock constructor to the start method.
public void start(int interval, final boolean beep)
{
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
} final int[] counter = new int[1]; (The array variable is still declared as final, but that merely means that you can’t have it refer to a different array. You are free to mutate the array elements.)
匿名内部类
When using local inner classes, you can often go a step further. If you want to make only a single object of this class, you don’t even need to give the class a name. Such a class is called an anonymous
inner class.
public void start(int interval, final boolean beep)
{
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
///////
}
};
} new SuperType(construction parameters)
{
inner class methods and data
} Here, SuperType can be an interface, such as ActionListener; then, the inner class implements that interface. Or SuperType can be a
class; then, the inner class extends that class.
本文详细介绍了Java中泛型接口的应用,特别是Comparable接口的增强,并深入探讨了内部类的使用方式及其如何访问外部类的变量。此外,还讲解了局部内部类的优势以及匿名内部类的使用场景。
1174

被折叠的 条评论
为什么被折叠?



