• 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 ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
  • Carey Brown
  • salvin francis
  • Claude Moore

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

Ranch Hand
Posts: 30
  • 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?
Saloon Keeper
Posts: 10136
  • 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?
Saloon Keeper
Posts: 20657
Android Eclipse IDE Java Linux Redhat Tomcat Server
  • 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.
And inside of my fortune cookie was this tiny ad:
Create Edit Print & Convert PDF Using Free API with Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!