1. 在方法重写时不能变更声明的返回类型,但可以为声明的返回类型的子类
-
public
class Foo{
-
void go() { }
-
}
-
class Bar extends Foo {
-
String go() {
// 不合法
-
return
;
-
}
-
}
该段代码会报如下错误
-
Multiple markers at
this line
-
- overrides Foo.go
-
- The
return type
is incompatible with
-
Foo.go()
但是如果在继承的同时还进行了重载,则声明的返回类型可以改变,如下代码能正常运行:
-
public
class Foo{
-
void go() { }
-
}
-
class Bar extends Foo {
-
String go(int x) {
-
return
;
-
}
-
}
重写的方法声明的返回类型可以为父类方法的子类:
-
public
class Foo{
-
Foo go(){
-
return
new Foo();
-
}
-
}
-
class Bar extends Foo {
-
Bar go() {
-
return
new Bar();
-
}
-
}
-
public
class Foo{
-
Foo go() {
-
return
;
-
}
-
}
3. return的类型可以为声明的返回类型的子类:
-
class Bar extends Foo {
-
Foo go() {
-
return
new Bar();
-
}
-
}
4. 当声明的返回类型为抽象类或者接口时,return的类型可以为继承该抽象类或者实现该接口的类:
-
abstract
class Foo{
-
abstract Foo go();
-
}
-
class Bar extends Foo {
-
Foo go() {
-
return
new Bar();
-
}
-
}
-
interface runnable{
-
runnable go();
-
}
-
class Bar implements runnable {
-
public runnable go() {
-
return
new Bar();
-
}
-
}
5. 当声明的发挥类型为void时,可以return但是不能return任何值,也不能return null,
-
abstract
class Foo{
-
abstract void go();
-
}
-
class Bar extends Foo {
-
public void go() {
-
return;
-
}
-
}
</div>
1. 在方法重写时不能变更声明的返回类型,但可以为声明的返回类型的子类
-
public
class Foo{
-
void go() { }
-
}
-
class Bar extends Foo {
-
String go() {
// 不合法
-
return
;
-
}
-
}
该段代码会报如下错误
-
Multiple markers at
this line
-
- overrides Foo.go
-
- The
return type
is incompatible with
-
Foo.go()
但是如果在继承的同时还进行了重载,则声明的返回类型可以改变,如下代码能正常运行:
-
public
class Foo{
-
void go() { }
-
}
-
class Bar extends Foo {
-
String go(int x) {
-
return
;
-
}
-
}
重写的方法声明的返回类型可以为父类方法的子类:
-
public
class Foo{
-
Foo go(){
-
return
new Foo();
-
}
-
}
-
class Bar extends Foo {
-
Bar go() {
-
return
new Bar();
-
}
-
}
-
public
class Foo{
-
Foo go() {
-
return
;
-
}
-
}
3. return的类型可以为声明的返回类型的子类:
-
class Bar extends Foo {
-
Foo go() {
-
return
new Bar();
-
}
-
}
4. 当声明的返回类型为抽象类或者接口时,return的类型可以为继承该抽象类或者实现该接口的类:
-
abstract
class Foo{
-
abstract Foo go();
-
}
-
class Bar extends Foo {
-
Foo go() {
-
return
new Bar();
-
}
-
}
-
interface runnable{
-
runnable go();
-
}
-
class Bar implements runnable {
-
public runnable go() {
-
return
new Bar();
-
}
-
}
5. 当声明的发挥类型为void时,可以return但是不能return任何值,也不能return null,
-
abstract
class Foo{
-
abstract void go();
-
}
-
class Bar extends Foo {
-
public void go() {
-
return;
-
}
-
}
</div>