Reputation: 151
Here in class animal getObjectSize on variable 'name' return 0
class Animal {
String name;
public Animal() {
System.out.println(ObjectSizeCalculator.getObjectSize(this.name));
}
}
Here in class Dog getObjectSize on variable 'dogName' return 0
class Dog extends Animal{
String dogName;
public Dog() {
System.out.println(ObjectSizeCalculator.getObjectSize(this.dogName));
}
public void dogplay(){
System.out.println("dog playing");
}
}
Here in class Main getObjectSize on Animal object return 16, but getObjectSize on Dog object return 24, but I thought it should return 16 just like animal object
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
Dog dog = new Dog();
long objectSize = ObjectSizeCalculator.getObjectSize(a);
long objectSize1 = ObjectSizeCalculator.getObjectSize(dog);
System.out.println(objectSize+" "+objectSize1);
}
}
What I think of is dogName reference size in memory equal 0, and name reference size in Animal class also equal 0, so why after creating a new object of Dog it has a larger size than animal object size?
When I remove (String dogName) from class dog, now Dog object size becomes equal to animal object size.
Upvotes: 0
Views: 148
Reputation: 109146
The problem is that you are using an incorrect assumption. The use of
System.out.println(ObjectSizeCalculator.getObjectSize(this.name));
in your constructor does not get the size of the reference this.name
, instead it gets the size of the object referred to by this.name
. Given in your code, this.name
is null
, the returned size is 0
.
Given instances of Animal
have 1 field (name
), and instances of Dog
have two fields (name
, inherited from Animal
, and dogName
), instances of Dog
will obviously need to be larger than instances of Animal
.
Upvotes: 3