子类是否能够重写父类的静态方法
重写:是根据运行时对象的类型决定调用哪个方法,如果这个类型在编译的时候已经确定了,那么即使子类拥有和父类相同的方法或属性,也非重写,而是子类覆盖了父类的方法。
package test2;
class Car{
static String color = "赤橙黄绿青蓝紫";
static int horsepower=1000;
static public void brand() {
System.out.println("这是一辆车,品牌未定");
}
static public void fly() {
System.out.println("这是一辆会飞的车");
}
}
class BMW extends Car{
static String color="白色";
static double horsepower=3000;
static public void brand(){
System.out.println("这是一辆宝马");
}
static public void fly() {
System.out.println("这是一辆会飞的车BMW");
}
}
public class Benz extends Car{
static String color = "红色";
static public void brand() {
System.out.println("这是一辆奔驰");
}
public static void main(String[] args) {
BMW bMW=new BMW();
Car car = new Benz();//在编译时,即确定了类型为Car,所以car.静态方法调用的是父类的
Benz benz=new Benz();
System.out.println(car.color); //赤橙黄绿青蓝紫
car.brand(); //这是一辆车,品牌未定
System.out.println(bMW.color);//白色
bMW.brand();//这是一辆宝马
System.out.println(bMW.horsepower);//3000
bMW.fly();//这是一辆会飞的车BMW
System.out.println(car.horsepower);//1000
car.fly();//这是一辆会飞的车
}
}
静态方法可以被继承,但是不能被重写。
可以被子类中同一个返回类型、方法名、参数列表的静态方法覆盖。
浙公网安备 33010602011771号