This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Return type question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply 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: 287


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://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Return type question
 
Similar Threads
GC question
Why compilation of the code fails here
VarArgs
returning a value
Protected and default access of a class member