Java – where are the private instance variables of the abstract class created in the heap?

abstract class A {
abstract class A {
    private int a;
    public A(int x) {
        a = x;
    }
    public int getA() {
        return a;
    }
}

class B extends A {
    public B(int x) {
        super(x);
    }
}

class TestB {
    public static void main(String args[]) {
        B b = new B(5);
        System.out.println(b.getA());
    }
}

In this case, when I say B = New B (5); Call the superclass constructor and initialize the private instance variable to 5 Therefore, when I say that geta () on an object of class B is referenced by B, it returns 5 Because the instance variable a of class A is private, it will not be inherited from level B Where is the instance variable a created (on the heap) If it is a public, it will become part of the class B instance on heap Class A is also an Abstarct class, so it cannot be instantiated

Solution

There is no difference in the allocation of instance variables, whether private, public, superclass or abstract superclass

Usually the sequence will be similar

>Reference b.class Object > object instance variable block (including auxiliary fields of GC, synchronization monitor,...) > block of an instance variable (only one in this case) > block of B instance variable (not in this case)

However, each implementation of the JVM is free to choose how to allocate them

And access control are enforced by the compiler and JVM

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>