1.什么是继承
当我们编写的多个类中存在相同的属性或方法时,可以将这些类中相同的属性和方法抽取到一个新的类中,然后再让这些类继承于这个新类,就可以重用新类中的属性和方法,这些类称为子类,这个新类称为父类,这就是Java中的继承。 2.如何使用继承
我们将上面的案例抽取出一个父类如下:
public class Animal {
String name;//名字
int age;//年龄
}接下来只需要继承于这个父类即可。在Java中,继承使用extends关键字 来表示,上面的三个类修改如下:
public class Cat extends Animal{//猫类继承于动物类
private String strain; //品种
//省略getter和setter方法
}
public class Dog extends Animal{//狗类继承于动物类
private String strain; //品种
//省略getter和setter方法
}
public class Penguin extends Animal{//企鹅类继承于动物类
private String sex; //性别
//省略getter和setter方法
}接下来我们可以编写一个测试案例。
public class AnimalTest {
public static void main(String[] args) {
Cat c = new Cat();
c.setName("苗苗");
c.setAge(1);
c.setStrain("咖啡猫");
}
}我们发现,在 Cat 类中并没有 setName 和 setAge 方法,但却可以直接使用这些方法,说明这两个方法都是从父类中继承过来的,其他两个类也一样。 3.子类能够继承父类的哪些属性和方法 3.1 API文档
在官方文档中有这样的描述:
A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent.
解释说明:
不论子类与父类是否在同一个包中,父类中使用 public 或者 protected 修饰的属性和方法,都能够被子类继承。如果子类和父类在同一个包中,那么子类还能继承受包保护的属性和方法(受包保护指的是没有使用访问修饰符的属性和方法)。
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
解释说明:
子类不会继承父类中定义的私有成员。但如果父类有提供使用 public 或者 protected 修饰的访问该字段的方法,这些方法也能在子类中被使用。
为了验证这些文档中的说法是否正确,接下来我们通过几个案例来进行验证。 3.2 案例一
public class Animal {
private String name;//修改访问修饰符为private
int age;//年龄
//省略getter和setter方法
}
public class Cat extends Animal {
private String strain;
public String getStrain() {
return strain;
}
public void setStrain(String strain) {
this.strain = strain;
}
public void show(){ //添加一个show方法,打印name和age属性
System.out.println(name + age);
}
}此时编译也出错,name 属性不能访问,但 age 属性可以。