Where is a private instance variable of an abstract class created in the heap?
source link: https://www.codesd.com/item/where-is-a-private-instance-variable-of-an-abstract-class-created-in-the-heap.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Where is a private instance variable of an abstract class created in the heap?
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 situation when i say B b=new B(5);
the super class constructor is called and the private instance variable is initialized to 5. So when i say getA()
on class B
's object reffered by b
it returns 5. As the instance variable a
of class A
is private it will not be inherited by the class B
. So where does the instance variable a
is created(on heap) . Had it been a public
it would have been a part of class B
instance on Heap. Also class A
is an abstarct class so it can not be instantiated.
there is no difference where the instance variables are allocated no matter if they are private, public, from a super class, from a abstract super class
typically the sequence will be something like
- reference to the
B.class
object - block of
Object
instance variables (including helper fields for GC, the monitor for synchronisation,...) - block of
A
instance variables (onlya
in this case) - block of
B
instance variables (none in this case)
however each implementation of a JVM is free to choose how it allocates each of them
and access control is enforced by both the compiler and the JVM
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK