简体   繁体   English

JVM如何创建抽象类的对象?

[英]How JVM creates object of abstract class?

I could not get how JVM gives output 10. We cannot create object of abstract class, then how JMV internally manages object creation of abstract class. 我无法了解JVM如何提供输出10。我们无法创建抽象类的对象,然后无法通过JMV在内部管理抽象类的对象创建。

abstract class A {
    int a = 10;
}

class B extends A {
    int a = 20; 
}

public class Sample {
    public static void main(String [] args) { 
        A obj = new B();
        System.out.println(obj.a); // prints 10
        System.out.println(((B)obj).a); // prints 20
    }
}

It doesn't create an instance of the abstract class A. It creates an instance of the concrete class B. 它不创建抽象类A的实例。它创建具体类B的实例。

However, since the variable obj used to hold the reference to the object is of type A, and since instance members (unlike methods) can't be overridden, obj.a returns the a variable of class A . 但是,由于可变obj用来保存参照对象是类型A的,并且由于实例成员(不像方法)不能被重写, obj.a返回a类的变量A

You can convince yourself that an instance of B was created by adding to your code : 您可以通过添加到代码中来使自己确信B的实例已创建:

public class Sample 
{ 
    public static void main(String [] args) { 
        A obj = new B(); 
        System.out.println(obj.a); // prints 10
        System.out.println(((B)obj).a); // prints 20
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM