基本作用:代码复用
重要作用:有了继承后才有方法覆盖和多态
语法:修饰符 class类名 extends 父类名{类体 = 属性 + 方法}
Java语言继承只支持单继承,一个类不能同时继承多类,c++可以
术语:B类继承A类
A类:父类,基类,超类,superclass
B类:子类,派生类,subclass
继承哪些数据:除了私有的,构造方法
可间接继承:
C extends B{}
B extends A{}
A extends D{}
C直接继承B,但是C间接继承A,D
Java语言中假设一个类没有继承任何类,该类默认继承javase库中提供的java.lang.Object类。Java语言任何一个类都有Object类的特征。
public class Test {
public static void main(String[] args) {
CreditAccount act = new CreditAccount();
act.setActno("act");
act.setBalance(10.1);
act.setCredit(0.1);
System.out.println(act.getActno() + "," + act.getBalance() + "," + act.getCredit() );
}
//账户类
public class Account {
private String actno;
private double balance;
public Account() {
super();
}
public Account(String actno, double balance) {
super();
this.actno = actno;
this.balance = balance;
}
public String getActno() {
return actno;
}
public void setActno(String actno) {
this.actno = actno;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
public class CreditAccount extends Account{
private double credit;
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
public CreditAccount() {
super();
}
}
}