1. 程式人生 > >java基礎複習(繼承和多型)

java基礎複習(繼承和多型)

  • 繼承中程式碼的執行順序
    1.父類靜態物件,父類靜態程式碼塊
    2 .子類靜態物件,子類靜態程式碼塊
    3.父類非靜態物件,父類非靜態程式碼塊
    4.父類建構函式
    5.子類非靜態物件,子類非靜態程式碼塊
    6.子類建構函式

  • 關於靜態方法的繼承:
    老師ppt上:
    1、與例項方法一樣,靜態方法能夠被繼承,但是靜態方法不能被重寫。
    2、如果父類和子類都定義了相同的靜態方法, 那麼父類中的靜態方法將會被隱藏。

    stackoverflow上
    Are static methods inherited in Java?

要點:
1、All methods that are accessible are inherited by subclasses

2、The only difference with inherited static (class) methods and inherited non-static (instance) methods is that when you write a new static method with the same signature, the old static method is just hidden, not overridden
(而overridden與hidden的重要區別在於:

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass

例項程式碼:

class A {
    public static void display() {
        System.out.println("Inside static method of superclass");
    }
}

class B extends A {
    public void show() {
        display();
    }

    public static void display() {
        System.out.println("Inside static method of this class"
); } } public class Test { public static void main(String[] args) { B b = new B(); b.display();//output:Inside static method of this class A a = new B(); a.display();//output:Inside static method of superclass } } /** * This is due to static methods are class methods. * * A.display() and B.display() will call method of their * respective classes **/

另外的補充:關於靜態fields
1、static field是不能被繼承的,但它們accessed by subclass

  • 物件型別轉換和instanceof運算子

    整體的規則是:
    1、You could always assign an instance of Class to a type higher up the inheritance chain.
    2、 You may then want to cast the less specific type to the more specific type

一般使用instanceof的原因是:

Basically, you check if an object is an instance of a specific class. You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).

型別轉換:
需要注意的是,向上型別轉換是隱式的,而向下(downcast)型別轉換則是強制的。
並且,在強制型別轉換時:
1、 if you try and cast objects in different inheritence hierarchies (cast a Dog to a String for example) then the compiler will throw it back at you because it knows that could never possibly work
2、滿足在同一個整合體系裡時:
Remember compiler is forced to trust us when we do a downcast
因此,不會產生編譯時錯誤。
3、但是當我們欺騙了編譯器時,比如轉換實際上是不能成立時,就會丟擲runtime error:ClassCastException
4、為了避免3類似的錯誤,就可以使用instanceof operator來檢驗