• super getClass()


    首先看一段代码:

    import java.util.Date;
    public class Test extends Date{
    public static void main(String[] args) {
    new Test().test();
    }
    public void test(){
    System.out.println(super.getClass().getName());
    }
    }


    上面这段代码的输出为:Test

    可能你会奇怪为什么输出的是Test,而不是Date呢?我明明是调用的super.getClass()啊。我们先不急,先来了解一下getClass()方法的机制是什么。以下时getClass()在Object类中实现的源代码。

    Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class. The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment: Number n = 0; Class<? extends Number> c = n.getClass(); Returns: The Class object that represents the runtime class of this object.                    getClass()方法: 返回此 Object 的执行时类。

    public final native Class<?> More ...getClass();  getClass()是final方法。子类无法重写。

    关键是理解super的含义:

    http://docs.oracle.com/javase/tutorial/java/IandI/super.html

    Using the Keyword super

    Accessing Superclass Members

    If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

    public class Superclass {
    
        public void printMethod() {
            System.out.println("Printed in Superclass.");
        }
    }
    

    Here is a subclass, called Subclass, that overrides printMethod():

    public class Subclass extends Superclass {
    
        // overrides printMethod in Superclass
        public void printMethod() {
            super.printMethod();
            System.out.println("Printed in Subclass");
        }
        public static void main(String[] args) {
            Subclass s = new Subclass();
            s.printMethod();    
        }
    }
    

    Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from SuperclassSubclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

    Printed in Superclass.
    Printed in Subclass

    使用super来引用 被子类覆盖的父类的方法。跟父类对象没有关系。

    用来引用一个方法而已。

  • 相关阅读:
    数据挖掘算法-Apriori Algorithm(关联规则)
    分类指标准确率(Precision)和正确率(Accuracy)的区别
    数据预处理(完整步骤)
    linux下使用tar命令
    (LeetCode 135) Candy N个孩子站成一排,给每个人设定一个权重
    海量数据处理算法—Bit-Map
    Python 3.x 连接 pymysql 数据库
    visio扩大画布的大小
    中文latex去掉图片描述
    LaTeX 中文段首空格问题
  • 原文地址:https://www.cnblogs.com/nulisaonian/p/6163554.html
Copyright © 2020-2023  润新知