Java中static和final修饰的方法是否能被子类继承

在Java中static和final修饰的方法是否能被子类继承

一、先说结论

  1. staticfinal修饰的方法能够被子类继承,但是不能被子类重写。
  2. privatestaticfinal修饰的方法不能加入虚方法表
  3. 方法是否能够加入虚方法表与是否能够被子类继承无关,但是与动态绑定和多态性有关。

二、证明

  1. 验证staticfinal修饰的方法能够被子类继承代码:
public class InheritanceTest {

    public static void main(String[] args) throws Exception{
        //通过反射获取GrandSon类中的所有public修饰的方法
        Class<?> clazz = Class.forName("inheritance.Child");

        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
    }
}

class Parent {

    public static void show1(){
        System.out.println("this is fu show1");
    }
    
    public final void show2(){
        System.out.println("this is fu show2");
    }

}

class Child extends Parent{

}

class GrandSon extends Child{

}

在上面的代码中通过获取GrandSon的字节码对象来获取该类中的方法,如果该类中存在show1show2这两个方法则证明这两个方法被继承给了子类。
运行代码结果如下:在这里插入图片描述
验证完毕。
2. 验证privatestaticfinal修饰的方法不能被加入到虚方法表代码:
在验证之前先说一个结论:Object类中可以加入到虚方法表中的方法个数为5个,因为Object是所有类的父类,因此我们下面计算类中虚方法的个数应该从5开始计算。使用jdk自带的内存分析工具HSDB可以看见每个类中虚方法表的长度(关于如何使用自行百度)

public class InheritanceTest {

    public static void main(String[] args){
         GrandSon grandSon = new GrandSon();
         //得到对象在虚拟机中的地址
         System.out.println(Long.toHexString(VM.current().addressOf(grandSon)));
         Scanner sc = new Scanner(System.in);
         sc.nextInt();
    }
}

class Parent {

    public static void show1(){
        System.out.println("this is parent show1");
    }
    
    public final void show2(){
        System.out.println("this is parent show2");
    }

    private final void show3(){
        System.out.println("this is parent show3");
    }
    
    public void show4(){
        System.out.println("this is parent show4");
    }

}

class Child extends Parent{

    @Override
    public void show4() {
        System.out.println("this is child show4");
    }
    
    public void eat(){
        System.out.println("this is child eat");
    }
}

class GrandSon extends Child{
    
}

先做假设:Parent中虚方法个数为 5+1=6个因为Parent中只有一个方法是非privatestaticfinal修饰的,Child中虚方法的个数为7个,GrandSon中也为7个。
中虚方法表长度为7
该图显示GrandSon中虚方法表的长度为7
该图显示中虚方法表的长度为7
该图显示Child中虚方法表的长度为7
中虚方法表长度为6
改图显示Parent中虚方法表长度为6
中虚方法表长度为5
改图显示Object中虚方法表长度为5

总结

以上就是关于staticfinal修饰的方法是否能被子类继承的验证,验证不一定正确,欢迎大家来讨论,共同进步。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值