Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Return type question

 
Herland Cid
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1310
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic