子类重写和隐藏父类的成员方法(Overriding and Hiding Methods)
2015-04-24 15:54
381 查看
先看一个例子:
public class Animal {public static void testClassMethod() {System.out.println("The static method in Animal");}public void testInstanceMethod() {System.out.println("The instance method in Animal");}}
</pre><pre name="code" class="html">public class Cat extends Animal {public static void testClassMethod() {System.out.println("The static 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 output:The static method in AnimalThe instance method in CatHere, The
Catclassoverrides the instance method in
Animaland hidesthe static method in
Animal. The
mainmethodin this class creates an instance of
Catand invokes
testClassMethod()onthe class and
testInstanceMethod()on the instance.Summary:
Instance Methods
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclassoverrides thesuperclass's method.The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding methodhas the same name, number and type of parameters, and return type as the method that it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.Static Methods
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.The distinction between hiding a static method and overriding an instance method has important implications:The version of the overridden instance method that gets invoked is the one in the subclass.The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.相关文章推荐
- java 子类继承父类成员变量的隐藏、实现方法的重写
- Java子类继承(二):隐藏成员变量和方法重写的理解
- 2018/01/07JAVA 基础 / 接口与继承:重写【子类继承并覆盖父类的对象方法】、隐藏【子类继承并覆盖父类的类方法】与实现类实现接口方法の区别
- 父类的正常成员函数子类可以使用,并不是继承下来 的,子类是怎么调用父类的函数 : 可能是利用了一种叫函数名联编的方法.没有隐藏的情况下用函数名字来决定调用的函数.
- 子类与父类之间的方法重载、隐藏、重写与虚方法调用
- java中重写(Overriding)和隐藏(Hiding)方法问题
- java中父类有static修饰的方法其子类能继承吗?若子类也有该方法,是覆盖还是重写?
- 子类重写父类方法时的方法权限变化
- Java中不要在父类的构造方法中调用会被子类重写的方法
- 关于父类静态方法能不能被子类重写详细
- php 父类调用子类方法和成员
- JavaSE8基础 多态 子类没有重写 父类引用调用父类中的方法
- C++11新特性:final和override 子类重写父类方法
- 为何Java中子类重写方法的访问权限不能低于父类中权限
- java 子类重写父类的方法
- Java的父类静态方法不能被重写,只能被隐藏
- 尝试创建一个父类和子类,分别创建一个构造方法,然后向父类和子类添加成员变量和方法,并总结构造子类对象时的顺序。
- 子类重写父类方法条件
- C#中子类对父类中虚方法的处理有重写(override)和覆盖(new),他们有什么区别?
- Java编程子类能否重写父类的静态方法探索