How does the JVM distinguish between method overloading and method overrides inside?

I would like to know how the JVM distinguishes between method overloading and method overriding inside.

+4
source share
4 answers

The JVM uses only the override method. The method is overridden by adding a method with the same signature in the derived class (the only allowed difference is the return type, which is more specific). The signature encodes the method name, as well as parameter types and return type.

" ", . javac , , .class. - Java .

+3

Jvm . .

, , Java .

, .

?

- , . , .

java. 1) 2)

java: , ,

.

1. , - . JVM . .

2. . Overriding .

, .

, , .

, "" "" . - "" .

+2

( ), JVM.

, .

, parent, child. parent, parent, parent . parent child, child .

, Java ( + JVM) , Mammal Human

public class OverridingInternalExample {

    private static class Mammal {
        public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); }
    }

    private static class Human extends Mammal {

        @Override
        public void speak() { System.out.println("Hello"); }

        // Valid overload of speak
        public void speak(String language) {
            if (language.equals("Hindi")) System.out.println("Namaste");
            else System.out.println("Hello");
        }

        @Override
        public String toString() { return "Human Class"; }

    }

    //  Code below contains the output and bytecode of the method calls
    public static void main(String[] args) {
        Mammal anyMammal = new Mammal();
        anyMammal.speak();  // Output - ohlllalalalalalaoaoaoa
        // 10: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V

        Mammal humanMammal = new Human();
        humanMammal.speak(); // Output - Hello
        // 23: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V

        Human human = new Human();
        human.speak(); // Output - Hello
        // 36: invokevirtual #7 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:()V

        human.speak("Hindi"); // Output - Namaste
        // 42: invokevirtual #9 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:(Ljava/lang/String;)V
    }
}

- javap -verbose OverridingInternalExample, , , .

java method constant pool

- , , , - humanMammal.speak(), human.speak() human.speak("Hindi") , . .

- anyMammal.speak() humanMammal.speak() , Mammal, , JVM , JVM , .

, JVM .

+1

, - , , . Java Java. , , Java, . , , . , ​​ , , Java. SO JVM
:

class Calculation{  
  void sum(int a,int b){System.out.println(a+b);}  
  void sum(int a,int b,int c){System.out.println(a+b+c);}   
}  

Method Override:

class Calculation{  
void sum(){System.out.println("sum in superclass");}  
}  
class Specific extends Calculation{  
void sum(){System.out.println("sum in Specific");}
}
0
source

All Articles