By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,737 Members | 1,971 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,737 IT Pros & Developers. It's quick & easy.

strange behavior

P: n/a
rvm
I do not understand why the following code will not compile.
However, if I change the function getElem() in class MyCollection
such that it returns an iElement (instead of MyElement), it
compiles fine. Does anybody understand the reasoning?!
interface iElement {
public int getVal();
}

interface iCollection {
public iElement getElem();
}

class MyElement implements iElement {
public int getVal() { return 0; }
}

class MyCollection implements iCollection {
public MyElement getElem() { return new MyElement(); }
}

Thanks in advance!
-Rick
Jul 17 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
> I do not understand why the following code will not compile.
However, if I change the function getElem() in class MyCollection
such that it returns an iElement (instead of MyElement), it
compiles fine. Does anybody understand the reasoning?!


Method signature must be the same both in definition and in implementation.
You would have the same error with class-superclass inheritance.

Luca Paganelli
Jul 17 '05 #2

P: n/a
rvm
Luca Paganelli wrote:
Method signature must be the same both in definition and in implementation.
You would have the same error with class-superclass inheritance.


This seems like an unnecessarily tight restriction to me. Shouldn't
this be allowed since the return of MyCollection's getElem() fits
the specification of the iCollection interface?

For example, the below code is accepted:
class A extends Exception {}
class B extends A {}

interface C {
public void test() throws A;
}

class D implements C
{
public void test() throws B {
throw new B();
}
}

Why doesn't the compiler accept this?:

interface C {
public A test() throws A;
}

class D implements C
{
public B test() throws B {
throw new B();
}
}

I can't think of a reason why this is not allowed.

-rvm
Jul 17 '05 #3

P: n/a
> This seems like an unnecessarily tight restriction to me. Shouldn't
this be allowed since the return of MyCollection's getElem() fits
the specification of the iCollection interface?


Method specified in your interface is more general than method
implemented in your class.
So a class implementing that interface can't be more restrictive
than the declaration itself. In other words your implementation
works only with MyElement whereas, as iCollection implementation,
it should work with _any_ iElement implementation!
--
Luca Paganelli
ICQ# 52629494
Jul 17 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.