猫和狗的继承(jdk-1.8)
首先创建猫和狗的类,声明变量,找到共同点(姓名,年龄),将共同点创建为父类:Animal.java
package EXTEND.Cats_and_Dogs; public class Animal { private String name; private String age; public Animal() { } public Animal(String name, String age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
然后继续修改猫、狗类
cat.java
package EXTEND.Cats_and_Dogs; public class Cat extends Animal{ public Cat() { } public Cat(String name, String age) { super(name, age); } public void catch_mouse() { System.out.println("Cat can catch the mouse"); } }
dog.java
package EXTEND.Cats_and_Dogs; public class Dog extends Animal{ public Dog() { } public Dog(String name, String age) { super(name, age); } public void protect_home() { System.out.println("Dog can protect the door"); } }
最后进行测试(需要在相同包下测试)
package EXTEND.Cats_and_Dogs; public class demo { public static void main(String[] args) { Cat c1 = new Cat("小黄", "7"); Cat c2 = new Cat("Tom", "5"); System.out.println(c1.getName() + ", " + c1.getAge()); System.out.println(c2.getName() + ", " + c2.getAge()); c1.catch_mouse(); c2.catch_mouse(); } }
注意:
cat和dog类中,先构造一个无参函数,再构造带参函数。
带参函数需要使用super()来访问父类的变量。
main中调用时直接传递参数即可。