继承的概念和实现
继承需要符合的关系:is-a;父类关系更通用更抽象,子类关系更特殊更具体
继承背后的思想:基于已存在的类来构建新类。当从已存在的类继承时,就重用了它的方法和属性,还可以添加新的方法和属性来定制新类以应对需求
约定:从其它类导出的叫子类,被导出的类叫父类
在Java中,除了Object类以外,所有类都是子类,都拥有唯一的父类
继承意义:代码重用+体现不同抽象层次
编程中:用extends表示一个类继承了另一个类
package jicheng.qybs.java;
class person
{
int age;
String name;
public void drink(){
System.out.println("人喝水");
}
public void eat(){
System.out.println("人吃饭");
}
}
class student extends person
{
double score;
public void gotoSchool(){
System.out.println("学生上学");
}
}
public class Test {
public static void main(String[] args) {
student s = new student();
s.name = "qybs";
s.eat();
s.gotoSchool();
}
}
super关键字
super和this相类似,但super代表的是父类的引用
子父类的成员出现同名时,可以用super来区分
子类的构造方法中,通过super关键字调用父类的构造方法
在子类构造方法中:第一条指令必须是调用父类构造方法!!!
package jicheng.qybs.java;
class person
{
int age;
String name;
public void drink(){
System.out.println("人喝水");
}
public void eat(){
System.out.println("人吃饭");
}
public person(String address,int data){
System.out.println("父类构造被调用");
}
}
class student extends person
{
public student(String address,int data){
super(address,data);
System.out.println("子类构造被调用");
System.out.println("address="+address+",data="+data);
}
double score;
public void gotoSchool(){
System.out.println("学生上学");
}
}
public class Test {
public static void main(String[] args) {
student s = new student("wang",111);
s.name = "qybs";
s.eat();
s.gotoSchool();
}
}