重写是子类对父类的容许访问的方法的实现过程进行从新编写!返回值和形参都不能改变。即外壳不变,核心重写!java
重写的好处在于子类能够根据须要,定义特定于本身的行为。ide
也就是说子类可以根据须要实现父类的方法。函数
在面向对象原则里,重写意味着能够重写任何现有方法。实例以下:spa
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)指定对象的类型而且运行该对象的方法。it
所以在上面的例子中,之因此能编译成功,是由于Animal类中存在move方法,然而运行时,运行的是特定对象的方法。io
思考如下例子:编译
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(); } }
以上实例编译运行结果以下:
TestDog.java:30: cannot find symbol symbol : method bark() location: class Animal b.bark(); ^
该程序将抛出一个编译错误,由于b的引用类型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(); // 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)); } }
区别点 | 重载方法 | 重写方法 |
---|---|---|
参数列表 | 必须修改 | 必定不能修改 |
返回类型 | 能够修改 | 必定不能修改 |
异常 | 能够修改 | 能够减小或删除,必定不能抛出新的或者更广的异常 |
访问 | 能够修改 | 必定不能作更严格的限制(能够下降限制) |