Java 中的方法重写
Java中的方法重写是如何实现的?在C++中,我们有vtable的概念。它在Java内部是如何实现的?
How is method overriding implemented in Java? In C++ we have the concept of vtable.. how is this implemented internally in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要回答这个问题,即具体如何在虚拟机中实现覆盖,可以在 Java 虚拟机编程(Google 图书链接)。
VM 将在引用的类中查找适当的方法定义,然后通过继承堆栈向上工作。显然,在某个阶段将应用各种优化。
有关相关字节码指令的说明,请参阅此处 >调用虚拟:
正如 gustafc 在下面强调的那样,可以应用各种优化,毫无疑问 JIT 将进一步引入。
To answer the question, which is specifically how overriding is implemented in the virtual machine, there's a write up available in Programming for the Java Virtual Machine (Google Books link).
The VM will look for an appropriate method definition in the referenced class, and then work its way up through the inheritance stack. Obviously at some stage various optimisations will apply.
See here for a description of the relevant bytecode instruction
invokevirtual
:As gustafc has highlighted below, various optimisations can apply, and no doubt the JIT will introduce further.
在重写 Java 中的任何方法时需要遵循的规则很少,不遵循这些规则会导致 Java 中的编译时错误。
There are few rules which needs to be followed while overriding any method in Java, failure to follow these rules result in compile time error in Java.
也许这是C++ Vtables 和 Java 的比较方法调用表很有趣。
Maybe this comparison of C++ Vtables and Java method invocation tables is of interest.
方法重写
这意味着在显示一些字符串的超级类中有一个方法可用,但是您想扩展这个类,并且您想打印您自己的方法,此时您需要覆盖这个方法到您的本地类中。
这是方法重写的基本介绍。
示例:
输出:
方法重写的优点是类可以为继承的方法提供自己的特定实现,而无需修改父类方法。
方法重写的规则是:
参数列表:参数列表必须相同。
访问修饰符:如果您要重写该方法,则必须为超类方法提供相同的修饰符,假设超类具有
public
方法,则您不能提供受保护
或私有
反之亦然。Method overriding
It means one method is available in supper class which is displaying some string, but you want to extend this class, and also you want to print your own method at that time you need to overriding this method into your local class.
This is a basic introduction to the method overriding.
Example:
OUTPUT:
Advantages of Method Overriding is that the class ca give its own specific implementation to an inherited method without any modifying the parent class method.
The rules of Method overriding are:
The argument list : the argument list must be the same.
Access Modifier : if you're overriding the method you must give the same modifier of super class method suppose super class have the
public
method you cannot give theprotected
orprivate
vice versa.只要您希望重写的函数(方法)未标记为
final
,您只需通过扩展保存该方法的类来重写该方法,然后提供具有相同签名但不同主体的方法。As long as the function (method) you wish to override is not marked as
final
you just simply override the method by extending the class which holds that method and then provide a method with same signature but different body.