开发者

Difference between B b and A<B> b

Ass开发者_C百科ume 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.


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.


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.


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.


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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜