Ganesh Pawar
Ganesh Pawar

Reputation: 25

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.

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
    }
}

Upvotes: 2

Views: 166

Answers (1)

Eran
Eran

Reputation: 393831

It doesn't create an instance of the abstract class A. It creates an instance of the concrete class 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.

You can convince yourself that an instance of B was created by adding to your code :

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
    } 
}

Upvotes: 4

Related Questions