Method overrides: Override: the need for inheritance, the parent class that subclasses override!
- Method name must be the same
- Parameter list must be the same
- Modifiers: could be expanded, but can not be reduced: public> protected> defalut> private
- Throws an exception: range, can be reduced, but not expand; ClassNotFoundException -> Exception
Rewriting, and methods of the parent class subclasses must be consistent; different method body!
Why do I need to rewrite?
- The parent class functions, sub-categories do not necessarily need, or may not meet!
- Alt+Insert:Override;
. 1 Package com.oop.demo05; 2 . 3 // rewriting method is overridden and independent properties . 4 public class B { . 5 public void Test () { . 6 System.out.println ( "B => Test" ) ; 7 } 8 }
1 package com.oop.demo05; 2 3 //继承 4 public class A extends B { 5 6 //Override 重写 7 @Override//注解:有功能的注释! 8 public void test() { 9 System.out.println("A=>test()"); 10 } 11 }
1 package com.oop; 2 3 import com.oop.demo05.A; 4 import com.oop.demo05.B; 5 6 public class Application { 7 8 public static void main(String[] args) { 9 10 //方法的调用只和左边,定义的数据类型有关 11 A a = new A(); 12 a.test();//A=>test 13 14 //父类的引用指向了子类 15 B b = new A();//子类重写了父类的方法,以子类重写过后的为准! 16 b.test();//A=>test 17 } 18 }