Java 2 实用教程 5.4 方法重写

方法重写。
1.重写的语法规则:如果子类可以继承父类的某个方法,那么子类就有权利重写这个方法。方法重写是指子类中定义一个方法,这个方法的类型和父类的方法的类型一致或者是父类的方法的类型的的子类型(所谓子类型是指,如果父类的方法是“类”,那么允许子类的重写方法的类型是“子类”),并且这个方法的名字,参数个数,参数的类型和父类完全相同。
子类如此定义的方法称做子类重写的方法(不属于新增的方法)。
2.重写的语法规则
子类通过方法的重写可以隐藏继承的方法,子类通过方法的重写可以把父类的状态和行为改变为自身的状态和行为。

下面是一个方法重写的例子。

University.java

package test;

public class University {
       void enterRule(double math,double english,double chinese)
       {
           double total =math+english+chinese;
           if(total>=180)
           {
               System.out.println(total+"分达到大学录取线");
           }
           else
               System.out.println(total+"分未达到大学录取线");
       }
}

ImportantUniversity.java

package test;

public class ImportantUniversity extends University {
       void enterRule(double math,double english,double chinese)
       {
           double total=math+english+chinese;
           if(total>=220)
           {
               System.out.println(total+"分达到重点大学录取线");
           }
           else
               System.out.println(total+"分未达到重点大学录取线");
       }
}

Example5_4.java

package test;

public class Example5_4 {
       public static void main(String args [])
       {
           double math=62,english=76.5,chinese=67;
           ImportantUniversity univer=new ImportantUniversity();
           univer.enterRule(math, english, chinese);
           math=91;
           english=82;
           chinese=86;
           univer=new ImportantUniversity();
           univer.enterRule(math, english, chinese);
       }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值