Tutorial :Difference between B b and A<B> b



Question:

Assume class B extends class A and I want to declare a variable for B. What is more efficient and why?

  1. B b OR
  2. A<B> b.


Solution:1

You are confusing two different concepts.

class B extends A {    }  

means that B is an A.

If you have something like A<B> it means that you class A is defined as

class A<T> {    }  

meaning that you class A is a generic class.

For example (over simplified) you have

class List<T> {    }  

So if T takes the value String you would have List<String> meaning a list of Strings

So A<B> does not mean that B extends A.

You should use B b.


Solution:2

Use B b. A<B> is a template class that uses B as a type, for example:

  • List<String> is a list of strings, so List<B> would be a list of B objects.

  • WeakReference<String> is a a weak reference to a string, so WeakReference<B> would be a weak reference to a B object.


Solution:3

If B extends A then I would use type A as much as possible.

A widget = new B();

This lowers the assumptions other parts of the code may make on your implementation.


Solution:4

I think it's not a matter of efficiency but of usage. If a pure A object isn't meant to use B, why would you want it to be A<B> b?


Solution:5

Your declarations don't do remotely the same thing. The first declares an object of type B, while the second declares an object of type A<T>, where T is a type parameter whose slot is filled by the type B.


Solution:6

Neither declaration is more efficient than the other.

But A<B> b doesn't declare a reference of type B, it declares a reference of type A that is templated on type B.

Unless A is a generic class, the second form is illegal.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »