接口的灵活性就在于“规定一个类必须做什么,而不管你如何做”。我们可以定义一个接口类型的引用变量来引用实现接口的类的实例,当这个引用调用方法时,它会根据实际引用的类的实例来判断具体调用哪个方法,这和上述的超类对象引用访问子类对象的机制相似。

 1 //定义接口InterA
 2 interface InterA
 3 {
 4  void fun();
 5 }
 6 //实现接口InterA的类B
 7 class B implements InterA
 8 {
 9  public void fun()
10  {
11   System.out.println(“This is B”);
12  }
13 }
14 
15 //实现接口InterA的类C
16 class C implements InterA
17 {
18  public void fun()
19  {
20   System.out.println(“This is C”);
21  }
22 }
23 
24 class Test
25 {
26  public static void main(String[] args)
27  {
28   InterA a;
29   a= new B();
30   a.fun();
31   a = new C();
32   a.fun();
33  }
34 }
View Code

相关文章:

  • 2021-11-18
  • 2021-04-20
  • 2021-11-03
  • 2022-01-08
  • 2021-08-17
  • 2022-12-23
  • 2021-12-29
猜你喜欢
  • 2021-11-20
  • 2022-12-23
  • 2021-07-07
  • 2022-12-23
  • 2021-11-16
相关资源
相似解决方案