Java继承代码案例,不多说,直接敲代码
Animal 类
/**
* @Author 公众号「MarkJava」
* @Date 2020/11/9 15:08
**/
public class Animal {
private String name;
private int month;
private String species;
public Animal() {}
public Animal(String name, int month, String species) {
this.name = name;
this.month = month;
this.species = species;
}
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;
}
@Override
public String toString() {
return "Animal{" +
"name='" + name + '\'' +
", month=" + month +
", species='" + species + '\'' +
'}';
}
}
Cat 类
/**
* @Author MarkJava
* @Date 2020/11/9 15:10
**/
public class Cat extends Animal{
private double weight;
public Cat(){}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
//跑步方法
public String run(){
return getName() + ",是一只属于" + getSpecies() + "的动物,它在奔跑中!";
}
}
Dog 类
/**
* @Author 公众号「MarkJava」
* @Date 2020/11/9 15:20
**/
public class Dog extends Animal{
private int age;
public Dog(){}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//狗会叫的方法
public String call(){
return getName()+ ",今年" + getAge() + "岁,它是属于" + getSpecies()+ "动物的,会旺旺地叫...";
}
}
测试类
/**
* @Author 公众号「MarkJava」
* @Date 2020/11/9 15:15
**/
public class Test {
public static void main(String[] args) {
//cat
Cat cat = new Cat();
cat.setName("白猫");
cat.setSpecies("猫类");
System.out.println(cat.run());
//Dog
Dog dog = new Dog();
dog.setName("旺财");
dog.setAge(2);
dog.setSpecies("狗类");
System.out.println(dog.call());
}
}