Ass开发者_C百科ume class B extends class A and I want to declare a variable for B. What is more efficient and why?
B b
ORA<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, soList<B>
would be a list ofB
objects.WeakReference<String>
is a a weak reference to a string, soWeakReference<B>
would be a weak reference to aB
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.
精彩评论