0

Are the both same?

ParentClass object=new ChildClass();

ParentClass object = (ParentClass) new ChildClass();

If I want to create a map which maps a string to Children Objects like

"dog"->childA;
"cat"->childB

How should I declare the Map?

Map<String,Parent>
or
Mpa<String,T extends Parent>

I am not sure if the second one is right or not but I read it somewhere

user2736993
  • 75
  • 1
  • 3
  • 10

3 Answers3

5

Are the both same?

Casting is unnecessary in the 2nd assignment. The first one is valid assignment. You can assign a child class object to super class reference.

How should I declare the Map?

You should declare it the first way. A Map<String, Parent> will be capable of holding instances of Parent or any of it's subclasses.

As for your 2nd declaration:

Map<String, T extends Parent>  // This won't compile

this is not the correct way to specify bound in type parameter while declaring map. You can't use bounded type parameter there. You should either use a wildcard bound, or just a type parameter - Map<String, T>, with bounds for T being declared where you declare that type (perhaps in the generic class where you declare the map). So, you can use <? extends Parent>. The issue with declaring map this way is that, you won't be able to add anything into it, accept null.

Related Post:

Reference:

Community
  • 1
  • 1
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

The cast and non-cast are indeed the same.

For the generic, if you declare it with <String, ? extends Parent>, you won;t be able to add things to the list due to the fact that if it was declared <String, Child> parents couldn't be added. If NewChild was created by another dev, then we can;t know if Parent, Child, or NewChild is used and writes would not be allowed.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

The first two are identical in effect. Casting is unnecessary.

If you want the map to contain a mixture of child classes, you need to declare

Map<String,Parent>

If you declare

Map<String,T extends Parent>

it declares a map from String to one particular child class of type T. The type parameter will need to be specified elsewhere (as a type parameter to the containing class or to an enclosing method). Note that you cannot instantiate a Map of an unbound type. Thus, for instance:

Map<String,? extends Parent> = new HashMap<String, ? extends Parent>();

generates a compiler error. The best you could do is:

Map<String,? extends Parent> = new HashMap<String, Parent>();

in which case you might as well stick with

Map<String,Parent> = new HashMap<String, Parent>();
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521