Java编程思想读书笔记-2(第8章)

2014-11-23 23:19:14 · 作者: · 浏览: 1
Java编程思想读书笔记 第2~7章


第8章 接口与内隐类


一. 接口

1. 如果实现接口的class未实现接口中的所有函数,则这个class必须被声明为abstract class,而接口中未被实现的函数在这个class中为abstract class。
  1. interface Interface{
  2. public void f();
  3. public void g();
  4. }
  5. abstract class First implements Interface{
  6. public void f(){}
  7. }
  8. class Second extends First{
  9. public void g(){}
  10. }
  11. public class ExplicitStatic{
  12. public static void main(String[] args){
  13. Interface f = new Second();
  14. f.f();
  15. f.g();
  16. }
  17. }

2. 接口中的所有函数自动具有public访问权限,所以实现某个接口时,必须将承袭自该接口的所有函数都定义为public
  1. interface MyInterface {
  2. public void f();
  3. void g();
  4. }
  5. class First implements MyInterface {
  6. public void f(){}
  7. //!void g(){}出错,应定义为public
  8. }

3. 接口中的数据成员自动成为static和final
  1. interface MyInterface{
  2. int i = 5;
  3. void f();
  4. void g();
  5. }
  6. class First implements MyInterface {
  7. public void f(){}
  8. public void g(){}
  9. }
  10. public class ExplicitStatic{
  11. public static void main(String[] args){
  12. MyInterface x = new First();
  13. // MyInterface的数据成员I为static,可直接调用
  14. System.out.println("MyInterface.i = " + MyInterface.i + " , x.i = " + x.i);
  15. // MyInterface的数据成员I为final,不能修改
  16. //x.i++;
  17. // MyInterface.i++;
  18. }
  19. }

4. 多重继承
1) devriced class可以同时继承多个interface和一个abstract或concrete base class。如果同时继承了base class和interface,那么要先写下具象类的名称,然后才是interfaces的名称。
2) 如果derived class所继承的具象类具有与interfaces相同的函数,则可在derived class不实现那个函数。
  1. interface CanFight{
  2. void fight();
  3. }
  4. interface CanSwim{
  5. void swim();
  6. }
  7. class ActionCharacter{
  8. public void fight(){}
  9. }
  10. class Hero extends ActionCharacter
  11. implements CanFight, CanSwim{
  12. public void swim(){};
  13. }
  14. public class ExplicitStatic{
  15. static void f(CanFight x) { x.fight(); }
  16. static void s(CanSwim x) { x.swim(); }
  17. static void a(ActionCharacter x) { x.fight(); }
  18. static void h(Hero x){
  19. x.fight(); x.swim();
  20. }
  21. public static void main(String[] args){
  22. Hero h = new Hero();
  23. f(h); s(h); a(h); h(h);
  24. }
  25. }

因为在Actio