1.没有super方法
/* * 子类方法覆盖父类方法,用super方法可以调用父类被覆盖的方法 */ class fruit{ public fruit() { System.out.println("fruit !"); } public void name() { System.out.println("我是水果!"); } } class apple extends fruit{ public apple() { System.out.println("apple !"); } public void name() { //super.name(); System.out.println("我是苹果!"); } } public class fugai { public static void main(String[] args) { apple a=new apple(); a.name(); } }
运行结果:
fruit !
apple !
我是苹果!
2.有super调用父类方法
1 class fruit{ 2 public fruit() { 3 System.out.println("fruit !"); 4 } 5 public void name() { 6 System.out.println("我是水果!"); 7 } 8 } 9 10 class apple extends fruit{ 11 public apple() { 12 System.out.println("apple !"); 13 } 14 15 public void name() { 16 super.name(); //调用父类被覆盖方法 17 System.out.println("我是苹果!"); 18 } 19 } 20 21 22 public class fugai { 23 24 public static void main(String[] args) { 25 apple a=new apple(); 26 a.name(); 27 } 28 29 }
运行结果如下:
fruit !
apple !
我是水果!
我是苹果!
父类的方法被调用
覆盖的规则
1.覆盖方法的允许范围不能小于原方法
2.覆盖方法所抛出的异常不能比原方法更多
3.声明为final方法不允许覆盖
4不能覆盖静态方法