Java三大体系之 多态
面对对象有三大特性:
1.封装
2.继承
3.多态
现在我们来讲第一个特性:多态
重写
在继承关系中,如果子类写了和父类方法签名完全相同的方法,叫做重写:
我们如下定义一个Person类
class Person {
public void run() {
System.out.println("Person.run");
}
}
再写一个Student子类,重写run方法
class Student extends Person{
@Override
public void run(){
System.out.println("Student.run");
}
}
这个就是重写。
多态
如果我们定义了一个Student类
Person Bob = new Student();
Bob.run();
那么run方法究竟是由Student类里面的方法运行,还是由Person类或者是他的子类去运行的呢?
那就得提起多态。
多态是指,针对某个类型的方法调用,其真正执行的方法取决于运行时期实际类型的方法。
super关键字
如果再重写方法中要调用父类被重写的方法,可以用到super关键字
class Person {
protected String name;
public String hello() {
return "Hello, " + name;
}
}
class Student extends Person {
@Override
public String hello() {
return super.hello() + "!";//调用父类方法
}
}
final关键字
如果父类中有方法不想被重写,可以用final修饰
class Person {
protected String name;
public final String hello() {
return "Hello, " + name;
}
}
同样,如果有类不想被继承,也可以用final所修饰
public final class Person{
.....
}
练习
小伙一个月的所得分为三种:基础工资(income),自己记件所得的工资(Salary),国务院津贴(StateCouncilSpecialAllowance)。income的税是0.1,Salary的税大于5000收0.2,津贴不收税。求所得税
package LiaoXueFeng.class_and_duixiang.Duo_Tai;
public class Tax {
public static void main(String[] args) {
Income[] incomes1 = new Income[] {
new Income(3000),
new Salary(7500),
new StateCouncilSpecialAllowance(15000)
};
System.out.println(totalTax(incomes1));
}
public static double totalTax(Income... incomes) {
double total = 0;
for (Income income: incomes) {
total = total + income.getTax();
}
return total;
}
}
class Income {
protected double income;
public Income(double income) {
this.income = income;
}
public double getTax() {
return income * 0.1; // 税率10%
}
}
class Salary extends Income {
public Salary(double income) {
super(income);
}
@Override
public double getTax() {
if (income <= 5000) {
return 0;
}
return (income - 5000) * 0.2;
}
}
class StateCouncilSpecialAllowance extends Income {
public StateCouncilSpecialAllowance(double income) {
super(income);
}
@Override
public double getTax() {
return 0;
}
}