Java方法重写

方法重写


如果子类中具有与父类中声明相同的方法,在java中称为方法重写。换句话说,如果子类提供了由其父类提供的其中一个方法的特定实现,则它被称为方法重写(覆盖)。所以方法重写有两个前提条件:继承和子父类中方法名称相同。

q)方法重写的用法

  • 在继承超类的同时,添加当前类的行为。
  • 方法重写用于运行时多态。

q)方法重写的条件

  • 首先得继承
  • 与父类中方法的名称相同
  • 与父类中方法的参数相同(这点容易和重载混淆)。

不重写的例子

class Vehicle {
    void run() {
        System.out.println("Vehicle is running");
    }
}
class Bike extends Vehicle {
    public static void main(String args[]) {
        Bike obj = new Bike();
        obj.run();                                                                                        //执行继承过来的父类run方法
    }
}

执行结果

Vehicle is running

这个是直接执行父类的方法,但我们只知道Vehicle启动了,而不知道具体的哪个Vehicle,这时我们可以加上重载

class Vehicle {
    void run() {
        System.out.println("Vehicle is running");
    }
}
class Bike extends Vehicle {
	@override
	void run() {
        	System.out.println("the Bike of Vehicle is running");
    	}

    public static void main(String args[]) {
        Bike obj = new Bike();
        obj.run();                                                                                        //执行重写后自己的run方法
    }
}

输出结果

the Bike of Vehicle is running

q)静态方法可以被重写吗?
静态方法不能被重写,静态方法不能被重写的原因

q)重载和重写的不同
java中的方法重载和方法重写有很多区别。 下面给出了方法重载和方法覆盖之间的差异列表:

方法重载方法重写
方法重载用于提高程序的可读性。方法重写用于提供已经由其超类提供的方法的特定实现。
方法重载在类内执行。方法重写需要继承到在子类中。
在方法重载的情况下,参数必须不同。在方法重写的情况下,参数必须相同。
方法重载是编译时多态性的例子。方法重写/覆盖是运行时多态性的例子。
返回类型任意子类的方法返回的权限修饰符必须大于等于所覆盖的方法

重载:

class OverloadingExample {
    static int add(int a, int b) {
        return a + b;
    }

    static int add(int a, int b, int c) {
        return a + b + c;
    }
}

重写

class Animal {
    void eat() {
        System.out.println("eating...");
    }
}

class Dog extends Animal {
    void eat() {
        System.out.println("eating bread...");
    }
}

q)不能重写的方法
不能被重写或者说覆盖的方法,指的是构造方法、静态方法、私有方法和final 修饰的方法。


版权声明:本文为weixin_43101144原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。