在Java中static和final修饰的方法是否能被子类继承
一、先说结论
static和final修饰的方法能够被子类继承,但是不能被子类重写。- 被
private、static和final修饰的方法不能加入虚方法表 - 方法是否能够加入虚方法表与是否能够被子类继承无关,但是与动态绑定和多态性有关。
二、证明
- 验证
static和final修饰的方法能够被子类继承代码:
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的字节码对象来获取该类中的方法,如果该类中存在show1和show2这两个方法则证明这两个方法被继承给了子类。
运行代码结果如下:
验证完毕。
2. 验证private、static和final修饰的方法不能被加入到虚方法表代码:
在验证之前先说一个结论: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中只有一个方法是非private、static、final修饰的,Child中虚方法的个数为7个,GrandSon中也为7个。

该图显示GrandSon中虚方法表的长度为7

该图显示Child中虚方法表的长度为7

改图显示Parent中虚方法表长度为6

改图显示Object中虚方法表长度为5
总结
以上就是关于static和final修饰的方法是否能被子类继承的验证,验证不一定正确,欢迎大家来讨论,共同进步。
902

被折叠的 条评论
为什么被折叠?



