• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

If the return type of my method is an interface name then what type of object is returned?  RSS feed

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What type of reference variable can reference to this object?
Is it any different from having my return type as my class name?

I got confused when the method navigableKeySet() returns a NavigableSet as its return type.

I referenced it using Set interface but now I am unsure which methods I can invoke on this object using my Set reference?
 
Bartender
Posts: 9487
184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general, casting is a bad idea.

Why do you need to cast at all? The method promises that it returns a NavigableSet, so just assign it to a variable of type NavigableSet, or Set, if you don't need the extra methods that NavigableSet provides.

The point of interfaces is that you don't need to care about the exact class that is returned. Why do you need HashSet?

A final remark: Don't initialize variables with values if you're immediately going to overwrite them anyway. Why create a new HashSet instance that you don't use when you're going to reassign the keyset variable on the next statement?
 
Bartender
Posts: 19954
94
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If keyset is defined as type Set, then any method defined in the Set interface can be invoked. However, the compiler and runtimes will both get offended if you attempt to invoke a method that's defined for a HashSet that's not defined in the Set interface. That's the one case where you'd have to cast keyset to a HashSet reference before invoking the method.

Casting is the bane of the C programming language. Since C does not have the built-in type-checking mechanisms, you can accidentally cast anything to anything, with potentially catastrophic results.

Java is a lot safer that way, in that casting is limited by the language environment to compatible types, but even there you can trigger a runtime exception if you are not careful.

So avoid casting if you can.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!