Search code examples
javaobjectinheritanceabstract-class

Difference in initialazing objects in java


Let's say I have an abstract class A and a class called B extending it. What's the difference between initializing like this:

A objectname=new B();

and this

B objectname=new B();  

Solution

  • In both cases you'd be creating an instance of B. The only difference is where you assign this instance. In the first snippet, objectname is of type A, so you won't be able to use B's methods that aren't in A unless you explicitly cast it to B.