r/javahelp • u/allexj • Jan 16 '21
If a class implements an interface, does this class ALWAYS have an "is a" relation with the interface? If not always, when it doesn't?
If a class implements an interface, does this class ALWAYS have an "is a" relation with the interface? If not always, when it doesn't?
15
u/mIb0t Jan 16 '21 edited Jan 16 '21
Yes, it has. In java you would use instanceof to to check this:
https://www.javatpoint.com/downcasting-with-instanceof-operator
It's the same for extend, not just implements.
Edit: Oh, I got my first award ever. Thank you 😊
9
5
u/sweetno Jan 16 '21
Always. At least this is what you should think about when declaring the interface and implementing it.
3
Jan 16 '21
Interface guarantees behavior would be be better words to describe interface as opposed to a class. Think of it this way, I don't care if you are a bot or a living person. I am just interested in chatting with you. If I type X, I am expecting Y typed in return. You can do it, a bot can also do it. So are you a bot? Or is bot a you?
If you can breathe and an elephant can breathe, then are you an elephant or is elephant a you?
Just because you can implement an abstracted behavior, does it define you? If you can spin about your own axis, are you the earth?
2
u/Mpittkin Jan 17 '21
The “is a” part is not saying something is X and only X. Just that of all the other things something might be, if it implements an interface X, you can treat it as an X.
I might have an interface
Namedwith a single methodString name(). If I have a list of those and want to print the names to the console, I don’t know or care anything about them other than that they are allNamedobjects and I can call that method and get a String back.It also doesn’t guarantee any behavior at all, that’s the implementation, which is not and should not be any concern of the client.
All it guarantees is that the implementing object adheres to the contract the interface specifies. In the previous example, that means there is a method
namewhich takes no arguments and returns a String.A better example might be an OutputStream. If all I know is that I have an OutputStream, I know which methods I can call and their parameters and return types, but without knowing the implementation I have no idea what behavior will result from calling them.
And that’s the beauty of it. Because if I’m writing some code to serialize some data to an OutputStream, it shouldn’t know or care what is going to happen to that data, so it’s not tied in any way to that underlying implementation. And then I can use the same code to write that data to a file, or a byte array, or send it across a network, etc., just by changing the type of OutputStream I pass in.
3
u/nutrecht Lead Software Engineer / EU / 20+ YXP Jan 17 '21
Just another resounding YES on the question. An ArrayList is a List. It doesn't have a list. A HashMap is a Map, it doesn't have a map.
The people who are answering 'no' here should really do a Java OO course.
1
1
u/Yithar Intermediate Brewer Jan 18 '21
Please stop double posting this on multiple subreddits and instead use the crosspost function, so people can avoid giving duplicate answers.
0
u/MysterAitch Jan 16 '21
There are two "is-a" relationships:
"has (makes real) the (theoretical abstract) behaviour of" (implements - realisation)
"is a specialised version of" (extends - specialisation)
A "Human" is a specialised version of "Animal" (Human extends Animal)
A "Human" has the behaviour of "Breather" (human implements Breather)
... Given this, the "technically correct I suppose" answer seems to be "yes" -- BUT whether it actually makes sense depends substantially on the name of the class and interface, and may be a nudge to reconsider the names of your classes/methods..
For example, given a (badly named) interface "Banana" that describes the behaviour (method) "grow()":
"Human is a Banana" vs "Human has the behaviour of Banana"
If we pick up on the code smell of this not making logical sense and rename Banana to Grower, it becomes:
"Human is a Grower" vs "Human has the behaviour of Grower"
8
u/feral_claire Software Dev Jan 16 '21
Your complicating this way more than it needs to be. Implementing an interface and extending a class aren't meaningfully different for types and both create an is-a relationship.
3
u/morhp Professional Developer Jan 16 '21 edited Jan 16 '21
If Human implements Banana then a human is a banana. Like you could write something like
Banana b = new Human();If this makes no sense, then your design is stupid. (no offense intended)Also you'd name this interface Growable (compare Comparable).
0
u/mw52588 Jan 16 '21
I wouldn't think of it as an "is a" relationship. A class that extends an abstract class is more of an "is a" relationship.
Think of an interface as a contract that you have to abide by. You can have one class that implements multiple interfaces. You have to implement all the methods from the interface. There's also a concept of coding to an interface. This allows you to change the implementation without breaking things.
For example an ArrayList implements a List interface. If you code to just an interface it will allow you to instead use a LinkedList but you won't have to change anything. This allows your code to be more modular and less coupled. Spring Framwork uses this concept to help achieve dependency injection.
2
u/morhp Professional Developer Jan 16 '21
I'd say that an ArrayList is a List and is a Collection and is a Object and is Serializable. There's no meaningful differences between abstract classes and interfaces here.
The main difference in the language is that interfaces may not define fields and you can implement multiple.
-4
Jan 16 '21
I don't understand the answers here that say "if class A implements Interface B, then A is-a B ". An interface is behavior with no state.
For example, a Device class might implement an interface Start that turns it on. The Start interface contains one method signature: void TurnOn(); .
A Device instance is not a Start.
Maybe I'm missing something.
13
u/isaacisaboss Jan 16 '21
For example, a Device class might implement an interface Start that turns it on. The Start interface contains one method signature: void TurnOn(); .
The standard reply would to retort that the "Start" interface is actually a Startable interface, and that the Device class implements Startable. Therefore, Device is-a Startable instance.
It's about behavior more than the choice of words.
7
u/GreenParsley Intermediate Brewer Jan 16 '21
Absolutely. Interfaces are never verbs and naming an interface(or a class or anything other than a method) "Start" is very confusing and therefore wrong.
3
u/dastardly740 Jan 16 '21
One of the reasons .NET naming conventions irritate me. Device is an IStartable.
That makes the code not align as well to how we speak. Then, what if you discover inheritance is better than an interface or vice versa... if you maintain naming conventions that refactor means changing every reference to IStartable or Startable in your code depending on which direction you go. And, then I get people who use the .NET conventions in Java.
3
u/feral_claire Software Dev Jan 16 '21
In your scenario a Device is-a Start. Why do you say it's not?
2
Jan 16 '21 edited Jan 16 '21
With code
public interface B { void doSomething (); } public class A implements B { public void doSomething() { System.out.println("Done!"); } } public class MainClass { public static void main(String[] args) { B thisIsB = new A(); } }The term "X is-a Y" means that an instance of X is assignable to a variable of type Y.
2
u/wildjokers Jan 16 '21
A Device instance is not a Start.
What? If Device implements Start (a horrible name for an interface) then Device absolutely is a Start.
1
Jan 17 '21
Why is Start a horrible name?
2
u/wildjokers Jan 17 '21
Interface names should be adjectives e.g. Iterable, Comparable, Writable, etc.
1
u/morhp Professional Developer Jan 17 '21
Well, or nouns like Stream, List, Map or Function. But not verbs.
1
u/quanture Jan 16 '21
While you're right that in practice you can use interfaces in a lot of different ways, people are so adamant about this because of the design convention taught in computer science curriculum about what it means to implement/inherit from an interface.
OP is connecting to that convention when they include the terms "is-a" and "has-a" in the post. Under that concept, implementing an interface is always an "is-a" relationship.
See this page as an example of how this is taught: https://www.w3resource.com/java-tutorial/inheritance-composition-relationship.php
1
u/morhp Professional Developer Jan 16 '21
A Device instance is not a Start.
Exactly. If you call an interface Start, I would expect it to contain information about that start, like a timestamp or reason.
What you want is a Startable interface. A device definitely is startable.
•
u/AutoModerator Jan 16 '21
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.