java--类继承和实现的接口中含有相同的方法

首先,说一下,当某一个类实现了两个接口的时候,两个接口中存在两个相同的方法,在实现的类中只需实现一个方法的方法体。

当一个类继承一个类,并且实现一个或者多个接口的时候,其中,父类和父接口中存在相同的方法。

  如果子类中存在该方法的实现体或者说是覆盖,则使用该类的对象去掉用该方法时候,其实掉用的是来自接口的实现方法,而不是来自父类方法的覆盖。

  如果子类中不存在该方法的实现[或者覆盖],在使用该类对象掉用该方法的时候,就会使用从父类继承的方法。同时将这个从父类继承来的方法当作接口方法的实现,也就可以不再实现接口的方法体。

另外值得注意的就是,extends & implements 的书写顺序不能改变。

 

为了方便记忆可以认为:接口的优先级别要高于父类。

此处附上代码:

 1 package Demo;

 2 

 3 interface CanFight {

 4     void fight();

 5 }

 6 

 7 interface CanSwim {

 8     void swim();

 9 }

10 

11 interface CanFly {

12     void fly();

13 }

14 

15 class ActionCharactor {

16     public void fight() {

17         System.out.println("fight() from class ");

18     }

19 }

20 

21 class Hero extends ActionCharactor 

22             implements CanFight, CanSwim, CanFly {

23     public void swim() {

24         System.out.println("Hero swim.");

25     }

26 

27     public void fly() {

28         System.out.println("Hero fly.");

29     }

30     public void fight(){

31         System.out.println("Hero can fight.");

32     }

33 }

34 

35 public class Demo1_1 {

36     public static void t(CanFight x) {

37         x.fight();

38     }

39 

40     public static void u(CanSwim s) {

41         s.swim();

42     }

43 

44     public static void w(ActionCharactor x) {

45         x.fight();

46     }

47 

48     public static void v(CanFly x) {

49         x.fly();

50     }

51 

52     public static void main(String[] args) {

53         // 向上转型

54         Hero hero = new Hero();

55         t(hero);

56         u(hero);

57         w(hero);

58         v(hero);

59         ActionCharactor a = new ActionCharactor();

60         a.fight();

61     }

62 }
View Code

 

你可能感兴趣的:(java)