1.继承
1)定义:一个类自动获得另一个类的属性或者方法的过程
2)使用:
父类:
public class Person {
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
子类:继承父类 并添加了自己新的方法
public class Doctor extends Person{
private String hospital;
public String getHospital() {
return hospital;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
}
3)java为单根继承 所有类都是Object的子类,缺省都继承了Object
4)基本原则:
a.构造器不能被继承
b.子类初始化时会默认情况调用父类缺省的构造器
c.子类调用父类的带参的构造器,则父类可以不提供缺省构造器
5)怎么使用继承
a.区分是“has a” 与 “is a” ,“is a”是继承关系
b.子类要扩充父类的功能
c.子类需要大量置换父类的功能时,不应该使用继承
6)继承的有缺点:
优点:a.继承是最容易的复用代码的形式
b.修改父类的功能时,子类可以自动获得新的功能
缺点:最大的缺点是打破封装,继承只是类型复用
2.权限控制
类成员修饰符 类内部 同包 子类 其他
private 是
default 是 是
protected 是 是 是
public 是 是 是 是
3.重写
1)定义:指子类重写父类中的方法
2)条件:
a.方法名相同
b.参数列表相同
c.返回值相同
d.子类的修饰符>=父类的修饰符
f.子类抽象方法抛出的异常<=父类抛出的异常
3)例子:
public class Account {
private String id;
private String name;
private double balance;
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
public Account(String name) {
this(name, 0);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
// 存款
public void deposit(double num) {
balance += num;
}
// 取款
public void debit(double num) {
balance -= num;
}
// 利息
public double getInterest() {
return 0;
}
}
上边的Account类 有个利息方法 默认返回0 子类覆盖给出新的实现
public class CheckingAccount extends Account
{
public CheckingAccount(String name, double balance){
super(name, balance);
}
public double getInterest(){
double interest=0;
if(getBalance()<=5000)
{
interest=getBalance()*0;
}
else if(getBalance()>5000 && getBalance()<=100000)
{
interest=getBalance()*0.01;
}
else if(getBalance()>100000)
{
interest=getBalance()*0.02;
}
return interest;
}
}
以上CheckingAccount 代表支票帐户 是Account的子类 覆盖了 获取利息的方法 给出了新的实现