2021/10/21
方法的覆盖:
class fu { public int age =40; public void show() { System.out.println("父亲的年龄" + age); } } class zi extends fu { public int age = 20; @Override public void show() { super.show(); System.out.println("儿子的年龄" + age); } } public class demo { public static void main(String[] args) { fu f = new fu(); f.show(); zi z = new zi(); z.show(); } }
方法覆盖的条件
(1)覆盖方法的允许访问范围不能小于原方法。
(2)覆盖方法所抛出的异常不能比原方法更多。
(3)声明为final方法不允许覆盖。 例如,Object的getClass()方法不能覆盖。
(4)不能覆盖静态方法。
多态:
public class ParentsChildTest { public static void main(String[] args) { Parent parent=new Parent(); parent.printValue();//Parent.printValue(),myValue=100 Child child=new Child(); child.printValue();//Child.printValue(),myValue=200 parent=child;//父类引用子类对象 parent.printValue();//Child.printValue(),myValue=200 parent.myValue++; parent.printValue();//Child.printValue(),myValue=200 ((Child)parent).myValue++; parent.printValue();//Child.printValue(),myValue=201 System.out.println(parent.age);//虽然引用的子类对象,但输出的确实父类中的age System.out.println(((Child)parent).age);//强制类型转换,此时输出的时子类的age } } class Parent{ public int myValue=100; public int age = 40; public void printValue() { System.out.println("Parent.printValue(),myValue="+myValue); } } class Child extends Parent{ public int myValue=200; public int age = 20; public void printValue() { System.out.println("Child.printValue(),myValue="+myValue); } }
Parent p = new Child();//父类引用子类对象
当用p对象调用成员变量时,输出的是父类的变量,而不是子类的
当调用方法时,若该方法在子类中被覆盖则调用子类中的该方法,则输出子类的;若父类中无该方法,子类中有,则报错
总的来说,当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。
浙公网安备 33010602011771号