举例子(父类:Animal 子类:Tiger)
1 public class TestAbstractAndInterface { 2 public static void main(String[] args) { 3 Tiger tiger = new Tiger("虎弟",3); 4 /* 5 * 1.sleep是直接继承Animal的 6 * 2.eat是重写的 7 * 3.preyOn和move都是接口中的 8 * */ 9 tiger.sleep(); 10 tiger.eat(); 11 tiger.preyOn(); 12 tiger.move(); 13 System.out.println("我的动物种类是"+Tiger.classname); 14 } 15 } 16 17 //抽象类中可以有非抽象的方法 18 abstract class Animal{ 19 20 private String name; 21 private int age; 22 //构造方法 23 public Animal(String name,int age) { 24 this.name = name; 25 this.age = age; 26 } 27 //抽象类中的非抽象方法 28 public void sleep() { 29 System.out.println("动物都是要睡觉的"); 30 } 31 //抽象方法就只要声明就好了,反正子类要重写 32 public abstract void eat(); 33 public String getName() { 34 return name; 35 } 36 public void setName(String name) { 37 this.name = name; 38 } 39 public int getAge() { 40 return age; 41 } 42 public void setAge(int age) { 43 this.age = age; 44 } 45 } 46 47 //接口中,全部是抽象方法,属性也是 public static final这种的 48 interface TigerImpl{ 49 public static final String classname = "老虎"; 50 public abstract void preyOn(); 51 public abstract void move(); 52 } 53 class Tiger extends Animal implements TigerImpl{ 54 55 //必须要父类的构造方法呀 56 public Tiger(String name, int age) { 57 super(name, age); 58 } 59 60 /* 继承抽象类 61 * 1.sleep这个非抽象的方法直接被继承了,你也可以重写 62 * 2.eat这个是抽象的方法,必须在子类种重写 63 */ 64 @Override 65 public void eat() { 66 System.out.println("老虎正在吃东西"); 67 } 68 69 /* 实现接口 70 * 1.捕食和移动方法都要重写 71 * 2.这个tigername这个变量应该也有的吧?? 72 */ 73 @Override 74 public void preyOn() { 75 System.out.println("我是"+this.getName()+",我正在捕食"); 76 } 77 78 @Override 79 public void move() { 80 System.out.println("我是"+this.getName()+",我正在移动"); 81 } 82 83 }
我的运行结果:
1 动物都是要睡觉的 2 老虎正在吃东西 3 我是虎弟,我正在捕食 4 我是虎弟,我正在移动 5 我的动物种类是老虎