`
paddy.w
  • 浏览: 497468 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Overriding and Hiding Methods

    博客分类:
  • Java
阅读更多
        方法的override体现在实例方法(instance method),hide体现在静态方法(class method)。

        满足下面几个条件,则构成了类继承关系间方法的override:
        1、相同方法名
        2、相同返回值
        3、相同参数,包括个数相同、类型相同
        可以将以上三个条件一起称为相同声明。(其实方法签名包括方法名+参数,但构成override还要包括返回值。编译器检查方法签名相同的时候会认定是同一个方法,强制返回值相同,如果override时返回值不同,编译器会报错
        注意:方法的访问修饰符对方法的override没有本质的影响。唯一需要注意的规范是:重写方法的访问权限必须大于被重写方法。

        对于继承类之间的两个具有相同声明的static方法,则构成了方法之间的hide。假设new一个子类型的对象,并声明为父类型。那么调用方法(父子之间构成hide的方法)时会调用父类型中的方法。也就是总是调用声明类中的方法(前提必须是父子之间的方法构成hide关系)。下面是java官方文档中的描述:
The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass.

        举一个例子:
public class StaticTest {

	public static void main(String[] args) {

		Test t=new Test2();
		t.print();

	}

}

class Test{
	protected static void print(){
		System.out.println("from Test");
	}
}

class Test2 extends Test{
	public static void print(){
		System.out.println("from Test2");
	}
}

        结果输出:from Test

        官方文档中有这么一个表格,清楚的看到父子类之间有相同声明的方法是构成重写、隐藏还是编译错误。
Subclass Instance MethodSuperclass Static Method
Subclass Instance MethodOverridesGenerates a compile-time error
Superclass Static MethodGenerates a compile-time errorHides

        简单说就是实例方法之间构成重写,类方法之间构成隐藏。实例方法和类方法之间会出现编译错误。

        官方文档链接:http://download.oracle.com/javase/tutorial/java/IandI/override.html
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics