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来检验

猜你喜欢

转载自blog.csdn.net/normol/article/details/78893271
今日推荐