1. static方法不能被重写
如下实例会出现编译错误:This instance method cannot override the static method from Animal
示例1:
class Animal {
public static void walk() { System.out.println("Animal行走方法"); }
}
public class Horse extends Animal {
public void walk() {
System.out.println("Horse四条腿行走");
}
public static void main(String [] args) {
new Horse().walk();
}
}
2. static方法可以被重载
示例2:
class Animal {
public static void walk() { System.out.println("Animal行走方法"); }
}
public class Horse extends Animal {
public void walk(String s) {
System.out.println("Horse四条腿行走");
}
public static void main(String [] args) {
new Horse().walk("");
}
}
运行结果如下:
Horse四条腿行走
示例3:
class Animal {
public static void walk() { System.out.println("Animal行走方法"); }
}
public class Horse extends Animal {
public static void walk() {
System.out.println("Horse四条腿行走");
}
public static void main(String [] args) {
new Horse().walk();
}
}
运行结果如下:
Horse四条腿行走
如果该代码去掉Horse中walk方法的static的话就变成示例1的情况,则编译不通过,
有static关键字则是在子类中进行该方法的重新定义,编译顺利通过。