重写是子类对父类的允许访问的方法的实现过程进行重新编写!返回值和形参都不能改变。即外壳不变,核心重写!
重写的好处在于子类可以根据需要,定义特定于自己的行为。
也就是说子类能够根据需要实现父类的方法。
在面向对象原则里,重写意味着可以重写任何现有方法。实例如下:
class animal{
public void move(){
system.out.println("动物可以移动");
}
}
class dog extends animal{
public void move(){
system.out.println("狗可以跑和走");
}
}
public class testdog{
public static void main(string args[]){
animal a = new animal(); // animal 对象
animal b = new dog(); // dog 对象
a.move();// 执行 animal 类的方法
b.move();//执行 dog 类的方法
}
}
以上实例编译运行结果如下:
动物可以移动
狗可以跑和走
在上面的例子中可以看到,尽管b属于animal类型,但是它运行的是dog类的move方法。
这是由于在编译阶段,只是检查参数的引用类型。
然而在运行时,java虚拟机(jvm)指定对象的类型并且运行该对象的方法。
因此在上面的例子中,之所以能编译成功,是因为animal类中存在move方法,然而运行时,运行的是特定对象的方法。
思考以下例子:
class animal{
public void move(){
system.out.println("动物可以移动");
}
}
class dog extends animal{
public void move(){
system.out.println("狗可以跑和走");
}
public void bark(){
system.out.println("狗可以吠叫");
}
}
public class testdog{
public static void main(string args[]){
animal a = new animal(); // animal 对象
animal b = new dog(); // dog 对象
a.move();// 执行 animal 类的方法
b.move();//执行 dog 类的方法
a.bark();//执行 animal 类的方法
}
}
以上实例编译运行结果如下:
testdog.java:30: cannot find symbol
symbol : method bark()
location: class animal
a.bark();
^
该程序将抛出一个编译错误,因为a的引用类型animal没有bark方法。
当需要在子类中调用父类的被重写方法时,要使用super关键字。
class animal{
public void move(){
system.out.println("动物可以移动");
}
}
class dog extends animal{
public void move(){
super.move(); // 应用super类的方法
system.out.println("狗可以跑和走");
}
}
public class testdog{
public static void main(string args[]){
animal b = new dog(); //
b.move(); //执行 dog类的方法
}
}
以上实例编译运行结果如下:
动物可以移动
狗可以跑和走
重载(overloading) 是在一个类里面,方法名字相同,而参数不同。返回类型呢?可以相同也可以不同。
每个重载的方法(或者构造函数)都必须有一个独一无二的参数类型列表。
只能重载构造函数
重载规则
public class overloading {
public int test(){
system.out.println("test1");
return 1;
}
public void test(int a){
system.out.println("test2");
}
//以下两个参数类型顺序不同
public string test(int a,string s){
system.out.println("test3");
return "returntest3";
}
public string test(string s,int a){
system.out.println("test4");
return "returntest4";
}
public static void main(string[] args){
overloading o = new overloading();
system.out.println(o.test());
o.test(1);
system.out.println(o.test(1,"test3"));
system.out.println(o.test("test4",1));
}
区别点 | 重载方法 | 重写方法 |
---|---|---|
参数列表 | 必须修改 | 一定不能修改 |
返回类型 | 可以修改 | 一定不能修改 |
异常 | 可以修改 | 可以减少或删除,一定不能抛出新的或者更广的异常 |
访问 | 可以修改 | 一定不能做更严格的限制(可以降低限制) |