• Post Reply Bookmark Topic Watch Topic
  • New Topic

Complicated question regarding Interfaces  RSS feed

 
Reedick Youlus
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd like to create a method that only takes objects that both implement that interface and are instances of a certain class or its subclasses, in order to make my program more secure.

In more detail, I have an Employee class, a Supervisor interface, and some supervisor classes that extend Employee and implement Supervisor. I want to make a method ("setSupervisor") in Employee that takes objects that must implement Supervisor and be instances of a subclass of Employee. How might I do this?

This is what I'm doing now (method only):
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch. Please check your Purple Mooseages for an administrative message.

About your question: There are multiple ways to do this.

You could do this dynamically, by using the instanceof operator to check at runtime if the object that was passed in is of a class that extends Employee and implements Supervisor. For example:

The disadvantage of doing this is that you won't notice a problem until runtime. The compiler won't give you any warning or error when you compile your code.

To check it at compile time instead of runtime, you could use generics. Then you'd get a compiler error if you'd try to call the method with something that doesn't implement Supervisor and extends Employee:

 
Reedick Youlus
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the response! I think I'll just use an exception, then.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Reedick Youlus wrote:Thanks for the response! I think I'll just use an exception, then.

Hmm. Odd that you would choose the less generic method; but it's up to you.

Alternatively - and this would be my choice - add an Employee interface, and have your Supervisor interface extend it. Then Supervisors can't be anything but Employees.

Winston
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote:
Reedick Youlus wrote:Thanks for the response! I think I'll just use an exception, then.

Hmm. Odd that you would choose the less generic method; but it's up to you.


That depends on what the OP means by: "make my program more secure".
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!