【java】继承和super.getClass()

本文深入探讨了Java中继承关系下getClass方法的行为,通过具体示例解释了返回当前运行时对象的class对象,强调了getClass方法的最终实现与返回值特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、先看问题

question:输出的结果是什么?

package cn.wxy.extendsion;
/**
 * 父类
 * @author reliveIT
 */
public class Father {

}
package cn.wxy.extendsion;

/**
 * 子类
 * @author reliveIT
 */
public class Son extends Father{
	public void show(){
		System.out.println(super.getClass());
	}
}

package cn.wxy.extendsion;

/**
 * 测试代码
 * @author reliveIT
 *
 */
public class TestDemo {
	public static void main(String[] args) {
		Son son = new Son();
		son.show();
	}
}

正解:class cn.wxy.extendsion.Son

二、或是解答

JKD api文档中关于Object getClass()方法的描述如下:

getClass
public final Class<?> getClass()返回此 Object 的运行时类。返回的 Class 对象是由所表示类的 static synchronized 方法锁定的对象。 
实际结果类型是 Class<? extends |X|>,其中 |X| 表示清除表达式中的静态类型,该表达式调用 getClass。 例如,以下代码片段中不需要强制转换:

Number n = 0; 
Class<? extends Number> c = n.getClass(); 


返回:
表示此对象运行时类的 Class 对象。
另请参见:
The Java Language Specification, Third Edition (15.8.2 Class Literals)
源码中关于getClass()方法的code如下:

 /**
     * Returns the runtime class of this {@code Object}. The returned
     * {@code Class} object is the object that is locked by {@code
     * static synchronized} methods of the represented class.
     *
     * <p><b>The actual result type is {@code Class<? extends |X|>}
     * where {@code |X|} is the erasure of the static type of the
     * expression on which {@code getClass} is called.</b> For
     * example, no cast is required in this code fragment:</p>
     *
     * <p>
     * {@code Number n = 0;                             }<br>
     * {@code Class<? extends Number> c = n.getClass(); }
     * </p>
     *
     * @return The {@code Class} object that represents the runtime
     *         class of this object.
     * @see    Class Literals, section 15.8.2 of
     *         <cite>The Java™ Language Specification</cite>.
     */
    public final native Class<?> getClass();


结论:getClass方法final修饰,因此不能被重写,因此无论是谁调用都调用了Object中final/native的该方法,根据描述(看不到具体的实现代码),getClass方法返回当前的运行时对象的class(字节码对象,即Class的实例对象),因此无论用super还是this修饰,返回的都是当前运行时对象的class。


附注:

        如有错漏,烦请指正,不胜感激!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值