1. 接口
在某些OOP语言中使用关键字protocol完成类似的功能。
字段隐式为final和static,方法隐式为public
2. 多重继承
一个非抽象类必须实现接口的所有方法,但实现的方法可以从父类中继承下来。
如interface1定义了两个方法f1()和f2(),father类定义了方法f1(),child类继承father类并实现接口interface1,它仅需要实现方法f2()即可。
3. 接口和抽象类的选择
如果知道某个事物应该成为一个基类,那个第一选择应该是使他成为一个接口。
4. 接口组合时的名字冲突
在打算组合的不同接口中使用相同的方法名常常会造成代码可读性的混乱,要尽量避免这种情况。
5. 群组常量
接口可以放便地用来创建常量组,就像C++中的enum枚举类型。
public interface Months {
int
JANURARY = 1; FEBRUARY = 2; //...
}
但这样不具备类型安全,如果需要类型安全,就需要构建一个final类
public final class Month {
private static Test monitor = new Test();
private String name;
private Month(String nm) { name = nm; }
public String toString() { return name; }
public static final Month
JAN = new Month("January"),
FEB = new Month("February"); //...
public static final Month[] month = {
JAN, FEB //...
};
public static final Month number(int ord) {
return month[ord - 1];
}
}
通过Month.number(int)获得Month类,由于每个月份的对象都仅存在一个,所以可以通过==或equals()判断是否相等。
枚举类也可以通过org.apache.commons.lang.enum包实现
6. 嵌套接口
内部接口可以被声明为private,而且可以被public类实现
As a new twist, interfaces can also be private, as seen in A.D (the same qualification syntax is used for nested interfaces as for nested classes). What good is a private nested interface? You might guess that it can only be implemented as a private inner class as in DImp, but A.DImp2 shows that it can also be implemented as a public class. However, A.DImp2 can only be used as itself. You are not allowed to mention the fact that it implements the private interface, so implementing a private interface is a way to force the definition of the methods in that interface without adding any type information (that is, without allowing any upcasting).
这段不是很理解。。。
另外,当实现某个接口时,并不需要实现嵌套在内部的任何接口。
7. 内部类与向上转型
内部类的真正好处在于,由于内部类--某个接口的实现--可以对其他人完全隐藏,他人所能得到的仅仅是一个基类或者接口的引用,而通过那个引用甚至不能找出该引用的最终类型,这样具体地实现就被完全隐藏了。
8. 在方法和作用域中的内部类
这么做的两个理由:
1)你实现了某类型的接口,于是可以创建并返回对其的引用。
2)你要解决一个复杂的问题,需要创建一个类来辅助你的解决方案,但有不希望这个类公共可用。
这种内部类只能在相应作用域内使用,除此以外,在编译等方面和普通的类一样。
9. 匿名内部类
很有用的一个方法,在用Netbeans开发界面的时候就发现它的事件响应代码就是用这个生成的。
startItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startItemActionPerformed(evt);
}
});
注意最后的分号。
如果匿名内部类要使用外部的对象,参数必须设置为final,否则就会产生编译错误。
那么如何产生类似构造器的行为呢?由于匿名,因此不可能存在构造器,但通过instance initialization,可以达到构造的效果。
public class AnonymousConstructor {
private static Test monitor = new Test();
public static Base getBase(int i) {
return new Base(i) {
{
System.out.println("Inside instance initializer");
}

public void f() {
System.out.println("In anonymous f()");
}
};
}
}
这里i不需要声明为final,因为在内部类中并没有被直接使用。
当然由于不支持重载,这类构造方法只能有一个

posts - 403, comments - 310, trackbacks - 0, articles - 7
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

2.20 - Java notes - Interfaces & Inner Classes

Posted on 2007-04-22 20:24 ZelluX 阅读(223) 评论(0)  编辑  收藏 所属分类: OOP
2007-02-20 13:52:16
只有注册用户登录后才能发表评论。


网站导航: