继承、重载、重写

方法的签名就是指方法名和参数列表

• 重写,英文名是overriding,是指在继承情况下,子类中定义了与其基类中方法具有相同方法签名的新方
法,就叫做子类把基类的方法重写了。
• 重载,英文名是overloading,是指在同一个类中定义了一个以上具有相同名称,但是方法签名不同的方
法。

可协变的返回类型:JAVA5.0SE之后,子类方法的返回类型可以是父类的子类。

代码示例:

1. class A {
2.     protected int method1(int a, int b) { return 0; }
3. }

public class B extends A{}

Which two are valid in class B that extends class A? (Choose two)
A. public int method1(int a, int b) { return 0; }
B. private int method1(int a, int b) { return 0; }
C. private int method1(int a, long b) { return 0; }
D. public short method1(int a, int b) { return 0; }
E. static protected int method1(int a, int b) { return 0; }

答案: A,C

A:可以

B: 子类的可见性不能比父类低,错误

C: 方法签名变了,属于和子类继承的method1方法的重载,而非重写。

D: 子类和父类的返回类型要一致

E : 不可以。编译器提示:This static method cannot hide the instance method from Inherit

 

原文地址:https://www.cnblogs.com/clara/p/2691049.html