方法重写
在 Java 继承中,也存在着重写的概念,其实就是子类定义了和父类同名的方法。
定义:方法名称相同,返回类型相同,参数也相同。代码如下:
package hello;
class Father01{
public void tell(){
System.out.println("父类调用方法");
}
}
class Son01 extends Father01{
public void tell(){
System.out.println("子类调用方法");
}
}
public class Demo02 {
public static void main(String[] args) {
Son01 son01 = new Son01();
son01.tell();
}
}
程序输出:
子类调用方法
重写限制
被子类重写的方法不能拥有比父类更加严格的访问权限。
访问权限:
private < default < public
注:属性或方法前面既不是 private 或 public,那么它的访问权限就是 default (省略不写)
代码如下:
package hello;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT;
class Father01{
public void tell(){
System.out.println("父类调用方法");
}
void print(){
}
}
class Son01 extends Father01{
public void tell(){
System.out.println("子类调用方法");
}
private void print(){
}
}
public class Demo02 {
public static void main(String[] args) {
Son01 son01 = new Son01();
son01.tell();
}
}
上述代码报错:
Cannot reduce the visibility of the inherited method from
Father01
因此在子类重写 print 方法时,子类 print 方法前添加了 private 属性,导致子类 print 方法比父类 print 方法访问权限严格,因此报错。
Super 关键字
Java 中通过 super 关键字完成对父类方法的调用,代码如下:
package hello;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT;
class Father01{
int age;
public void tell(){
System.out.println("父类调用方法");
}
void print(){
System.out.println("父类 print");
}
}
class Son01 extends Father01{
public void tell(){
System.out.println("子类调用方法");
}
void print(){
super.print();
System.out.println("子类 print");
}
}
public class Demo02 {
public static void main(String[] args) {
Son01 son01 = new Son01();
son01.print();
}
}
Java 重写和重载的区别
区别 | 重载 | 重写 | |
1 | 单词 | Overloading | Overriding |
2 | 定义 | 方法名称相同,参数的类型或者个数不同 | 方法名称,参数的类型和个数完全相同 |
3 | 权限 | 对权限没有要求 | 被重写的方法不能比父类拥有更严格的访问权限 |
4 | 范围 | 发生在一个类中 | 发生在继承中 |