方法重写。
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);
}
}