继承可以解决代码复用,当多个类有相同的属性和方法时,可以定义一个父类,在父类中定义相同的属性和方法,子类在定义自己特有的属性和方法的同时可以直接继承(extends)父类中所有的属性及方法
细节:
public class Testtest{
public static void main(String[] args){
Cat cat = new Cat("刮刮乐", 3, 10.8);
System.out.println(cat.Test());
Dog dog = new Dog("奶酪",20,12);//
System.out.println(dog.Test());
}
}
//父类
class Animal{
private int age;
public double high;
//父类无参构造器
public Animal(){
System.out.println("父类无参构造器被调用");
}
//父类有参构造器
public Animal(int age, double high){
setAge(age);
this.high = high;
}
//封装
public void setAge(int age){
if(age <= 15 && age >= 1){
this.age = age;
}else{
System.out.println("age不在范围内,已设定为2岁");
this.age = 2;
}
}
public int getAge(){
return age;
}
}
//子类
class Cat extends Animal{
private String name;
public Cat(String name, int age, double high){
super(age, high);//用super调用指定的父类有参构造器
this.name = name;
}
public String Test(){
return "name =" + this.name + " 今年" + getAge() + "岁了" + "有" + high + "高";
}//非私有的high可以直接访问,私有的age借助主类的公共方法访问
}
//子类
class Dog extends Animal{
private String name;
public Dog(String name, int age, double high){//什么都不写默认调用父类无参构造
this.name = name;
setAge(age);
this.high = high;
}
public String Test(){
return "name =" + this.name + " 今年" + getAge() + "岁了" + "有" + high + "高";
}//非私有的high可以直接访问,私有的age借助主类的公共方法访问
}