• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface as reference type

 
Guillermo Ishi
Ranch Hand
Posts: 789
C++ Linux Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are the rules for interfaces as reference types? Any difference from other objects as a reference type?
 
Henry Wong
author
Marshal
Pie
Posts: 22094
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If an object implements the interface, it IS-A that interface type, and hence, it can be assigned to a reference variable of that interface type.

Henry
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With regard to casting (and/or using the instanceof operator) there's an intricate difference between 2 classes and a class and an interface.

As you probably know it's impossible (as in "compilation fails") to cast (and/or use the instanceof operator) with 2 incompatible types (as in "not part of the same class hierarchy), e.g.

But for a class and an interface, there's a little gotcha. If casting (and/or) is allowed (as in "no compiler errors") depends on the class being marked final or not. More info in this excellent post. (Disclaimer: it's one of my own posts, so I might be a little bit biased )
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic