`
atmosphere
  • 浏览: 14125 次
  • 性别: Icon_minigender_1
博客专栏
807a8b01-317a-34bf-9d0f-011a7c5a74b4
javase7官方教程翻译...
浏览量:10679
社区版块
存档分类
最新评论

JAVASE官方教程:继承之重写和隐藏方法(7)

阅读更多

实例方法

一个与父类中的实例方法有相同标签(名字,参数个数和类型)和返回类型的子类实例方法会重写父类中的方法.

 

子类重写的方法具有修改对象的行为的能力,他也可以返回被重写方法返回类型的子类型.这叫做协变返回类型(covariant return type).

 

在重写某个方法时,你可能想用@Override注解来告诉编译器你打算重写父类中的某个方法.这时候,如果编译器不能在父类中找到这样的方法,将会产生一个错误.


类方法

如果子类中定义了一个类方法与父类中的某个类方法具有相同的标签,那么子类中的方法隐藏(hides)了父类中的方法.

 

重写和隐藏的区别有重要的意义.调用重写的方法是子类中的版本,调用隐藏的方法的版本依赖于你是用子类还是用父类来调用的.让我们看一个例子:

public class Animal {
    public static void testClassMethod() {
        System.out.println("The class method in Animal.");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Animal.");
    }
}

public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The class method in Cat.");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;
        Animal.testClassMethod();
        myAnimal.testInstanceMethod();
    }
}

 

 

输出:

The class method in Animal.
The instance method in Cat.

 

修饰符

访问修饰符的权限只能比在父类中更大或者一样.例如,父类中有个protected实例方法,在子类中修饰符可以是public或protected,但不能是private.

 

小结

下面的表格总结了当你定义一个与父类中的方法居于相同的标签时会发生什么.

 

 

  父类中的实例方法 父类中的静态方法
子类中的实例方法 重写 编译时错误
子类中的静态方法 编译时错误 隐藏
1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics