Java三大体系之多态

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值