- 继承是Java面向对象编程当中一种代码复用的方法
- Java只允许单继承
- proteced关键字把访问权限控制在子类与父类之间
- 若父类的构造方法没有参数,子类可以默认调用;若父类的构造方法有参数,子类必须显示用super()调用父类的构造方法
- 可以安全地向上转型为更为抽象的类型
- 向下转型时最好用instanceof先判断
public class Person {
protected String name;
protected int age;
protected String gender;
public Person(String name){
this.name=name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void run(){
System.out.println(name +" is running");
}
}
public class Student extends Person {
private int score;
public Student(String name){
/**
* 必须显示地调用父类的构造方法
*/
super(name);
System.out.println("Student class create");
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
/**
* 父类protecetd的属性允许被子类访问
*/
public void hello(){
System.out.println(this.gender);
}
}
来源:CSDN
作者:weixin_45215505
链接:https://blog.csdn.net/weixin_45215505/article/details/104575411