Override Method in Java

How is method overriding implemented in Java? In C ++, we have the concept of vtable .. how is this implemented inside Java?

+3
source share
5 answers

To answer the question, in particular, how redefinition is implemented in a virtual machine, there is an entry available in Programming for a Java virtual machine (Google Books Link).

The VM will look for a suitable method definition in the reference class, and then pave the way through the inheritance stack. Obviously, at some stage various optimizations will be applied.

See here for a description of the corresponding bytecode instruction invokevirtual:

invokevirtual ( ). . objectref . objectref - . invokevirtual Java objectref , , methodname, - .

gustafc , , , , JIT .

+12

, supper, , , , .
.

eg.
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 Dpg();
    d.displayMessage();
  }
}

OUTPUT:

Overriding , ca - .

.

: .
: , , , , .... etc

0

Java - , OOPS , . Java, .

, Java, Java.

  • Java , . .
  • Java: Super Sub, .
  • Java , Java. , , overriding , private package-private; Java, , .
  • Java , , , . , IOException, , java.lang.Exception throws, java.lang.Exception IOException . RuntimeException Java, throws Java.
  • , Java. , Java . Java . , .
  • Java .
  • , , . .
  • Always use the @Override annotation when overriding a method in Java. Although this is not the rule, it is one of the best Java coding practices. From Java 6, you can use the @Override annotation for a method inherited from the interface.
0
source

As long as the function (method) that you want to override is not marked as final, you simply simply override this method, expanding the class that supports this method, and then provides a method with the same signature but with a different body.

-1
source

Source: https://habr.com/ru/post/1719710/


All Articles