面向对象的特征(二) 继承
多个类中存在相同属性和行为时,将这些内容抽取到单独一个类中,那么多个类无需再定义这些属性和行为,只要继承那个类即可
class Subclass extends Superclass{ }
作用:
1.继承提高了代码的复用性。
2.继承让类与类之间产生了关系,提供了多态的前提。
3.不要仅为了获取其他类中某个功能而去继承
特点:
1.子类继承了父类,就继承了父类的方法和属性。
2.在子类中,可以使用父类中定义的方法和属性,也可以创建新的数据和方法。
3.在Java 中,继承的关键字用的是“extends”,即子类不是父类的子集,而是对父类的“扩展”。
规则:子类不能直接访问父类中私有的(private)的成员变量和方法。
java中类的继承是单继承。
方法的重写:
在子类中可以根据需要对从父类中继承来的方法进行改造,也称方法的重置、覆盖。在程序执行时,子类的方法将覆盖父类的方法。
1.重写方法必须和被重写方法具有相同的方法名称、参数列表和返回值类型。
2.重写方法不能使用比被重写方法更严格的访问权限。
3.重写和被重写的方法须同时为static的,或同时为非static的
4.子类方法抛出的异常不能大于父类被重写方法的异常
super关键字:
1.super可用于访问父类中定义的属性
2.super可用于调用父类中定义的成员方法
3.super可用于在子类构造方法中调用父类的构造器
PM:
1.尤其当子父类出现同名成员时,可以用super进行区分
2.super的追溯不仅限于直接父类
3.super和this的用法相像,this代表本类对象的引用,super代表父类的内存空间的标识
public class Person {
protected String name;
protected int age;
int id = 1001;
public Person() {
//super();
System.out.println("这是Person空参的构造器!");
this.name = "AA";
this.age = 1;
}
public Person(String name) {
this();
this.name = name;
}
public Person(String name, int age) {
this(name);
this.age = age;
}
=====
public class Student extends Person {
private String schoolName;
int id = 1002;
public Student() {
super();
}
public Student(String schoolName) {
super("lily", 18);
this.schoolName = schoolName;
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public void show() {
System.out.println(this.id);// 1002
System.out.println(super.id);// 1001
}
}
子类对象的实例化过程:
/**
* 子类对象实例化过程
* 注意内存中的运行过程
* @author Administrator
*
*/
public class TestCat {
public static void main(String[] args) {
Cat c =new Cat();
c.setAge(3);
c.setName("小花");
c.setColour("black");
System.out.println("name: "+c.getName() + " age: "+c.getAge() + " colour: "+c.getColour());
}
}
class Creature{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Creature() {
super();
}
}
class Animal extends Creature{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Animal() {
super();
}
}
class Cat extends Animal{
private String colour;
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public Cat() {
super();
}
}