重写是子类对父类的允许访问的方法的实现过程进行重新编写!返回值和形参都不能改变。即外壳不变,核心重写!
重写的好处在于子类可以根据需要,定义特定于自己的行为。
也就是说子类能够根据需要实现父类的方法。
在面向对象原则里,重写意味着可以重写任何现有方法。实例如下:
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 类的方法 |
b.bark(); |
} |
} |
当需要在子类中调用父类的被重写方法时,要使用super关键字。
以上实例编译运行结果如下:
动物可以移动 |
狗可以跑和走 |
重载(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)); |
} |
} |
区别点 | 重载方法 | 重写方法 |
---|---|---|
参数列表 | 必须修改 | 一定不能修改 |
返回类型 | 可以修改 | 一定不能修改 |
异常 | 可以修改 | 可以减少或删除,一定不能抛出新的或者更广的异常 |
访问 | 可以修改 | 一定不能做更严格的限制(可以降低限制) |