Reputation: 69
I am new in Functional Interface and today i am learning from few of tutorial sites. I have a question plz provide your suggestions and guide me.
Below mentioned code have an question for me.
@FunctionalInterface
interface Demo {
Object clone(); // protected
//int hashCode(); // public
//boolean equals(Object c); // public
//public void wait(); // final so we cannot override this one.
}
Object class is parent for all java classes. Here wait() method says not overrided because this one is final. So it means Demo interface also child of Object class (in general terms).
> @FunctionalInterface means interface with exact one method declaration.
Question: So, Now code is working when Object clone(); method is not commented. So means this method is declared in interface Demo. But when we click on its implementation we move on Object class's clone() method.
When we comment clone() method and un-comment equals() method, then we get compile time error, interface is not FunctionalInterface. Why ?????? and why its functional interface with clone() method.
Please don't say clone() is protected, what's the matter if clone is protected in Object class. Please explain for me.
Thanks, sawai
Upvotes: 1
Views: 113
Reputation: 31689
It's because clone()
is protected. I know you asked me not to say that, but I'm going to say it anyway because it's the answer.
http://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.8 specifically says:
For an interface I, let M be the set of abstract methods that are members of I that do not have the same signature as any public instance method of the class Object. Then, I is a functional interface if there exists a method m in M for which both of the following are true:
The signature of m is a subsignature (§8.4.2) of every method's signature in M.
m is return-type-substitutable (§8.4.5) for every method in M.
Note that it says public instance. When you've uncommented clone()
, this is a method that does not have the same signature as a public instance method, because clone()
in Object
is a protected instance method. Thus, your clone()
method will satisfy the conditions. You can't say the same about equals()
, since equals()
is a public instance method in Object
. That means that the set M referred to by this rule is empty, and therefore the method m that must be in this set cannot exist.
There's a comment in the JLS a couple paragraphs down which explains why they decided to treat clone()
differently.
Upvotes: 2
Reputation: 4091
Since public boolean equals(Object c)
already exists in Object
, Demo
doesn't declare any new method. To be a FunctionalInterface
, it should declare only one method.
When instead you declare public Object clone()
, it is a new method because the original one in Object
is protected
. Therefore it can be considered as a FunctionalInterface
.
Upvotes: 0