java多态、重写(OverRideing)

来源:互联网 发布:内核是什么知乎 编辑:程序博客网 时间:2024/06/12 01:26

首先要先说明一点:

重写是多态,重载不是多态

        多态性是指允许将父类对象(接口)设置为一个或者多个与子类对象(接口实现类)相等的技术。赋值之后,父对象就可以根据复制给他的自对象的特征以不同方式运作。意思是:父类的方法被子类继承后表现出不同的行为。不同层次的类,又相同的方法,但是有不同的表现。

        多态的关键是晚绑定,是运行期的行为,而重载(OverLoading)是编译期的行为,因此重载不是多态


1.有继承(或实现)

2.有重写

3.要有父类(接口)的对象指向子类(实现类)的引用。在编译期为父类对象,父类中未定义的方法不能调用;运行期为子类对象,子类中重写过的方法被执行子类的方法。


重写:

0.参数列表必须相同

1.访问修饰符不能比父类更严格

2.父类中用final修饰的方法不能被重写

3.父类中用static修饰的方法,在子类不能有重名且参数列表相同的普通方法,同名的静态方法不构成重写

4.返回值类型与被重写方法的返回值相同或返回值的子类

5.重写的方法不能抛出比被重写方法的声明或抛出的更大的异常



public class Parent{String s = "String Parent";public static void p(){System.out.println("Parent");}}

public class Child extends Parent{String s = "String Child";// This instance method cannot override the static method from Parent        // 会报错,无法重写父类的静态方法/*public void p(){}*/public static void p(){System.out.println("Child");}public void p(int i){}}



public class Main{public static void main(String[] args){Parent parent = new Child();Child child = new Child();parent.p(); //The static method p() from the type Parent should be accessed in a static wayParent.p();<span style="white-space:pre"><span style="font-size:14px;">// 使用类名调用静态方法执行自己类中的静态方法</span></span>Child.p();System.out.println(parent.s);<span style="white-space:pre"><span style="font-size:14px;">//调用属性,是调用声明对象的属性</span></span>System.out.println(child.s);}}


// 打印结果

Parent
Parent--// 使用类名调用静态方法执行自己类中的静态方法
Child
String Parent--//调用属性,是调用声明对象的属性
String Child


引用类型的转换

向上转型:子类型转为父类型 Praent p = new Child();(隐式转换)

向下转型:父类型转为子类型 Child() c = (Child)p; (显示转换)(父类的引用指向子类的对象是前提,否则会出错)java.lang.ClassCastException





0 0
原创粉丝点击