28.Java基础_抽象类

纵饮孤独 提交于 2019-12-06 10:52:33

抽象类的成员特点

 1 public abstract class Animal {
 2     private String name;
 3     private int age;
 4     public Animal() {
 5     }
 6     public Animal(String name, int age) {
 7         this.name = name;
 8         this.age = age;
 9     }
10     public String getName() {
11         return name;
12     }
13     public void setName(String name) {
14         this.name = name;
15     }
16     public int getAge() {
17         return age;
18     }
19     public void setAge(int age) {
20         this.age = age;
21     }
22     public abstract void eat();
23 }
24 
25 
26 public class Cat extends Animal{
27     public Cat() {
28     }
29     public Cat(String name, int age) {
30         super(name, age);
31     }
32     @Override
33     public void eat(){
34         System.out.println("猫吃鱼!");
35     }
36 }
37 
38 public class Dog extends Animal{
39     public Dog() {
40     }
41     public Dog(String name, int age) {
42         super(name, age);
43     }
44     @Override
45     public void eat(){
46         System.out.println("狗吃骨头!");
47     }
48 }
49 
50 public class test {
51     public static void main(String[] args) {
52         //创建对象
53         //无参
54         Animal a1=new Cat();
55         a1.setName("加菲");
56         a1.setAge(5);
57         Animal b1=new Dog();
58         b1.setName("小黑");
59         b1.setAge(6);
60         //有参
61         Animal a2=new Cat("加菲",5);
62         Animal b2=new Dog("小黑",6);
63 
64         //输出
65         a1.eat();
66         a2.eat();
67         b1.eat();
68         b2.eat();
69     }
70 }

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!