File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Return type question

Herland Cid

Joined: Feb 28, 2013
Posts: 15
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: 1118

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:
subject: Return type question
It's not a secret anymore!