Java 中的方法重写

发布于 2024-08-07 10:35:29 字数 58 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

叹倦 2024-08-14 10:35:29

要回答这个问题,即具体如何在虚拟机中实现覆盖,可以在 Java 虚拟机编程(Google 图书链接)。

VM 将在引用的类中查找适当的方法定义,然后通过继承堆栈向上工作。显然,在某个阶段将应用各种优化。

有关相关字节码指令的说明,请参阅此处 >调用虚拟:

invokevirtual 查看描述符
给出 , 并确定
该方法需要多少个参数
(这可能为零)。它弹出这些
参数离开操作数堆栈。下一个
它将 objectref 从堆栈中弹出。
objectref 是对象的引用
正在调用谁的方法。
invokevirtual 检索 Java 类
查找 objectref,并搜索列表
该类定义的方法和
然后是它的超类,寻找
方法名为methodname,其
描述符就是描述符。

正如 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:

invokevirtual looks at the descriptor
given in , and determines
how many arguments the method takes
(this may be zero). It pops these
arguments off the operand stack. Next
it pops objectref off the stack.
objectref is a reference to the object
whose method is being called.
invokevirtual retrieves the Java class
for objectref, and searches the list
of methods defined by that class and
then its superclasses, looking for a
method called methodname, whose
descriptor is descriptor.

As gustafc has highlighted below, various optimisations can apply, and no doubt the JIT will introduce further.

梦回旧景 2024-08-14 10:35:29

Java中的方法重写是一个基于多态OOPS的概念
允许程序员创建两个同名方法的概念
接口上的方法签名及其各种实现和
实际方法在运行时调用,具体取决于对象的类型
运行时。方法重写允许您编写灵活且可扩展的代码
使用 Java 编写代码,因为您可以用最少的时间引入新功能
代码更改。

在重写 Java 中的任何方法时需要遵循的规则很少,不遵循这些规则会导致 Java 中的编译时错误。

  1. 关于 Java 中方法重写的第一个也是最重要的规则是,您只能重写子类中的方法。您不能覆盖同一类中的方法。
  2. Java中方法重写的第二个重要规则是,超类和子类或接口及其实现中的方法的名称和签名必须相同。
  3. Java 中重写方法的第三条规则是重写方法不能降低 Java 中被重写方法的可访问性。例如,如果重写方法是公共的,则重写方法不能是受保护的、私有的或包私有的;但相反的是,重写方法可以增加Java中方法的可访问性,即如果重写方法是受保护的,则重写方法可以是受保护的或公共的。
  4. Java中方法重写的另一个值得注意的规则是,重写方法不能抛出比被重写方法层次更高的检查异常。这意味着如果重写方法抛出 IOException ,则重写方法不能在其 throws 子句中抛出 java.lang.Exception ,因为 java.lang.Exception 在异常层次结构中高于 IOException 。此规则不适用于 Java 中的 RuntimeException,甚至不需要在 Java 的 throws 子句中声明。
  5. 你不能覆盖Java中的私有、静态和最终方法。私有方法和静态方法在编译时使用 Java 中的静态绑定进行绑定,并且在运行时不会解析。 Java中重写final方法是编译时错误。虽然私有和静态方法可以隐藏,如果您在子类中声明具有相同和签名的另一个方法。
  6. 重写方法是在运行时根据对象类型在 Java 中使用动态绑定来调用的。
  7. 如果您要扩展抽象类或实现接口,则需要重写所有抽象方法,除非您的类不是抽象的。抽象方法只能通过方法重写来使用。
  8. 在 Java 中重写方法时始终使用 @Override 注解。虽然这不是规则,但它是值得遵循的最佳 Java 编码实践之一。从 Java 6 开始,您也可以在从接口继承的方法上使用 @Override 注释。

Method overriding in Java is a concept based on polymorphism OOPS
concept which allows programmer to create two methods with same name
and method signature on interface and its various implementation and
actual method is called at runtime depending upon type of object at
runtime. Method overriding allows you to write flexible and extensible
code in Java because you can introduce new functionality with minimal
code change.

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.

  1. First and most important rule regarding method overriding in Java is that you can only override method in sub class. You can not override method in same class.
  2. Second important rule of method overriding in Java that name and signature of method must be same in Super class and Sub class or in interface and its implementation.
  3. Third rule to override method in Java is that overriding method can not reduce accessibility of overridden method in Java. For example if overridden method is public than overriding method can not be protected, private or package-private; But opposite is true overriding method can increase accessibility of method in Java, i.e. if overridden method is protected than overriding method can be protected or public.
  4. Another worth noting rule of method overriding in Java is that overriding method can not throw checked Exception which is higher in hierarchy than overridden method. Which means if overridden method throws IOException than overriding method can not throw java.lang.Exception in its throws clause because java.lang.Exception comes higher than IOException in Exception hierarchy. This rule doesn't apply to RuntimeException in Java, which is not even need to be declared in throws clause in Java.
  5. You can not override private, static and final method in Java. private and static method are bonded during compile time using static binding in Java and doesn't resolve during runtime. overriding final method in Java is compile time error. Though private and static method can be hidden if you declare another method with same and signature in sub class.
  6. Overridden method is called using dynamic binding in Java at runtime based upon type of Object.
  7. If you are extending abstract class or implementing interface than you need to override all abstract method unless your class is not abstract. abstract method can only be used by using method overriding.
  8. Always use @Override annotation while overriding method in Java. Though this is not rule but its one of the best Java coding practice to follow. From Java 6 you can use @Override annotation on method inherited from interface as well.
猛虎独行 2024-08-14 10:35:29
--Defining the same method with the same method signature(i.e. same number/type of arguments and same return type/s.)in base and derived class.
--Which method is to be called is decided  at runtime so, it is also called runtime polymorphism/late binding. 
--we should override the method defined in the superclass.
--when the method is called the method defined in the subclass is called and executed instead of the one in superclass.
--we overcome this by use of 'super' keyword.
//program
class A
{
void disp(){
System.out.println("class A");
}

}
class B extends A
{
public void disp(){
System.out.println("class B");

}
}
public class ExampleIdea{
public static void main(String[] args){
A a  = new B(); //Parent reference but B class object (we can achieve polymorphism when parent class reference is used to refer a child class object) 
B b = new B();    //B class reference and B class object
A c = new A();
a.disp(); //runs the method in B class 
b.disp();  //runs the method in B class
c.disp();  //runs then method in A class
}
}//end of program

when we run this output will be class B.

In order to access the function of class A we have to use super keyword
as:

 class B extends A
{
public void disp(){
System.out.println("class B");
super.disp();
}
--Defining the same method with the same method signature(i.e. same number/type of arguments and same return type/s.)in base and derived class.
--Which method is to be called is decided  at runtime so, it is also called runtime polymorphism/late binding. 
--we should override the method defined in the superclass.
--when the method is called the method defined in the subclass is called and executed instead of the one in superclass.
--we overcome this by use of 'super' keyword.
//program
class A
{
void disp(){
System.out.println("class A");
}

}
class B extends A
{
public void disp(){
System.out.println("class B");

}
}
public class ExampleIdea{
public static void main(String[] args){
A a  = new B(); //Parent reference but B class object (we can achieve polymorphism when parent class reference is used to refer a child class object) 
B b = new B();    //B class reference and B class object
A c = new A();
a.disp(); //runs the method in B class 
b.disp();  //runs the method in B class
c.disp();  //runs then method in A class
}
}//end of program

when we run this output will be class B.

In order to access the function of class A we have to use super keyword
as:

 class B extends A
{
public void disp(){
System.out.println("class B");
super.disp();
}
绝對不後悔。 2024-08-14 10:35:29

方法重写
这意味着在显示一些字符串的超级类中有一个方法可用,但是您想扩展这个类,并且您想打印您自己的方法,此时您需要覆盖这个方法到您的本地类中。
这是方法重写的基本介绍。

示例:

class Animal
{
  public void displayMessage()
  {
    System.out.println("Animal is eating");
  }
  
}
class Dog extends Animal
{
  public void displayMessage()
  {
    System.out.println("Dog is eating");
  }
  public static void main(String arg[])
  {
    Dog d=new Dog();
    d.displayMessage();
  }
}

输出:

Dog is eating

方法重写的优点是类可以为继承的方法提供自己的特定实现,而无需修改父类方法。

方法重写的规则是:

  • 参数列表:参数列表必须相同。

  • 访问修饰符:如果您要重写该方法,则必须为超类方法提供相同的修饰符,假设超类具有 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:

class Animal
{
  public void displayMessage()
  {
    System.out.println("Animal is eating");
  }
  
}
class Dog extends Animal
{
  public void displayMessage()
  {
    System.out.println("Dog is eating");
  }
  public static void main(String arg[])
  {
    Dog d=new Dog();
    d.displayMessage();
  }
}

OUTPUT:

Dog is eating

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 the protected or private vice versa.

沫尐诺 2024-08-14 10:35:29

只要您希望重写的函数(方法)未标记为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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文