Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

kb QUESTION PG 617

 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The above code doesn't complie and gives error . can't add person
Please advise and correct if any code added in code.
 
Matt Russell
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you're extending a generic version of HashSet, you need to override the add method with a Person argument, not an Object, like this:
 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So i need to correct my add method

public boolean add(Person o)
{
return super.o;
}

Could please teel wht super.o will do..

Correct me if i am wrong
 
Matt Russell
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need super.add(o), rather than super.o. That will call the implementation of add() in HashSet, the superclass of Group, and will add the person to the HashSet. There's not much point to the override, as the HashSet add() method would have been called in any case.
 
Ninad Kulkarni
Ranch Hand
Posts: 802
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
name clash: add(java.lang.Object) in Group and add(E) in java.util.HashSet<Person> have the same erasure, yet neither overrides the other
public class Group extends HashSet<Person> {
^

I got above error while compiling please explain it

I keep signature of the method public boolean add(Object o)as it is
while compiling
 
Bert Bates
author
Sheriff
Posts: 8900
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Dinesh,

It would be good to understand what part of the question's answer was confusing?

Thanks,

Bert
 
Madhukar Ojha
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Signature of your add method must be like this .

public boolean add(Person o)
{
return super.add(o);
}

Because HashSet is instantiated with type parameter Person .
Hence add method of HashSet class will take Person object only .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic