Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Return type question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Return type question" Watch "Return type question" New topic
Author

Return type question

Herland Cid
Greenhorn

Joined: Feb 28, 2013
Posts: 6
Studying for this exam, I have a return type question. I don't understand why Fig 1 is illegal but Fig 2 is legal, any hints? thanks

Fig 1:

public class Foo{
void go(){ }
}

public class Bar extends Foo {
String go () { //Illegal code
return null;
}

}

------
Fig 2:

class Alpha {
Alpha doStuff(char c) {
return new Alpha();
}
}

class Beta extends Alpha {
Beta doStuff(char c) { // legal override in Java 1.5
return new Beta();
}
}

Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 722


Bar overrides go in Foo. When a method overrides another method, overriding method's return type should be the same as or subtype of that of the overriden method.


Yes, since JDK 1.5, overriding method can have the return type , which is a subtype of the return type in the overriden method.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Return type question
 
Similar Threads
VarArgs
Protected and default access of a class member
Why compilation of the code fails here
returning a value
GC question