Java继承实例代码
Java继承实例代码
目录结构
animal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.geekmubai.animal; public class Animal { private String name; private int month; private String species; public Animal() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } //吃东西 public void eat(){ System.out.println(this.getName()+"在吃东西"); } } |
cat
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.geekmubai.animal; public class Cat extends Animal { private double weight; public Cat() { } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } //跑动的方法 public void run(){ System.out.println(this.getName()+"是一只"+getSpecies()+"的猫,他在跑。"); } } |
dog
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.geekmubai.animal; public class Dog extends Animal { private String sex; public Dog() { } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } //睡觉的方法 public void sleep(){ System.out.println(this.getName()+"现在"+this.getMonth()+"个月大,在睡觉。"); } } |
test
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.geekmubai.test; import com.geekmubai.animal.Cat; import com.geekmubai.animal.Dog; public class Test { public static void main(String[] args) { Cat one=new Cat(); one.setName("十二"); one.setSpecies("中华田园猫"); one.eat(); one.run(); System.out.println("================="); Dog two=new Dog(); two.setName("负十二"); two.setMonth(2); two.eat(); two.sleep(); } } |