简体   繁体   English

Java中不同类的重写方法

[英]Overriding methods from different classes in java

From a java tutorial Java教程

  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. 与实例的超类相同的包中的子类可以覆盖未声明为私有或最终的任何超类方法。

  • A subclass in a different package can only override the non-final methods declared public or protected. 不同包中的子类只能覆盖声明为public或protected的非最终方法。

What is the difference though?If a method is not declared private then it must be public or protected no? 但是有什么区别呢?如果一个方法没有被声明为私有方法,那么它必须是公共的或没有保护的?

This points can be rephrased as: you can override only method to which your class have access to, and if this method is not final . 这一点可以改写为: 您只能覆盖类可以访问的方法,并且此方法不是final的

So if you are creating class outside of package in which base class (or interface) is placed you can override only non-final public and protected methods. 因此,如果要在放置基类(或接口)的包外部创建类,则只能覆盖非最终的公共方法和受保护的方法。

If derived class is in same package as base class then you can also override non-final methods without access modifier (package-protected). 如果派生类与基类在同一包中,则您也可以覆盖没有访问修饰符(受包保护)的非最终方法。

You can never override private methods. 您永远不能覆盖私有方法。

Actually, no. 其实没有

A method can be public, protected, private or package private . 方法可以是public,protected,private或package private The method is package private if you don't specify an access modifier. 如果您未指定访问修饰符,则该方法是包私有的。

It's obvious why a class from a different package cannot overwrite package private members. 很明显,为什么来自其他程序包的类不能覆盖程序包私有成员。

The difference is the default (or package-private ) access modifier. 区别在于default (或package-private )访问修饰符。 If you don't specify an access modifier, then only other classes in the same package can access it, regardless of whether they are subclasses or not. 如果您未指定访问修饰符,则只有同一包中的其他类可以访问它,无论它们是否是子类。

For more information: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html 有关更多信息: http : //docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM