Passing null values ​​to overloaded methods in java | variables are overloaded - exception type

I practice some examples in Java. The code is as follows:

public class NullPassing {
    public static void main(String[] args) {
        method1(null);
    }
    public static void method1(Exception e) {
        System.out.println(e);
    }
    public static void method1(ArithmeticException e) {
        System.out.println(e);
    }
}

I have a few questions regarding this,

1) The above code executes and prints zero using method1 (ArithmeticException e), why doesn't it use an exception (since the top of the hierarchy)?

Guess: this is due to a more specific variable ArithmeticExceptioncompared to Exception. If so, why is Question-2

2) By entering the following code into existing code, the program shows a compile-time exception. Why?

public static void method1(NullPointerException e) {
    System.out.println(e);
}

Help me learn. Thanks

+4
source share
3 answers

1 . , , , , .

JLS ( 15.12.2.5):

- , . Java , . , , , , , , .

( , " ".)


/ :

public class NullPassing {
    public static void main(String[] args) {
        method1(null);
    }
    public static void method1(Exception e) {
        System.out.println(e);
    }
    public static void method1(ArithmeticException e) {
        System.out.println(e);
    }
    public static void method1(NullPointerException e) {
        System.out.println(e);
    }  
}

(, " " ). , , , . .

, , null; .

  method1((NullPointerException)null)
+2

,

 public static void method1(Exception e) {
 }
 public static void method1(ArithmeticException e) {
 }

null, , , ArithmeticException - Exception, , , , ArithmeticException .

public static void method1(Exception e) {
}
public static void method1(ArithmeticException e) {
}
public static void method1(NullPointerException e) {
}

, , , NullPointerException, ArithmeticException, , , , .

+2

1. ArithmeticException?

Java . "[ ]", - ; ArithmeticException.

, Java , . : fooobar.com/questions/1253222/...

2. , NullPointerException?

, , Java : method1(NullPointerException) method1(ArithmeticException) . , , null : . method1((NullPointerException)null).

. fooobar.com/questions/124360/...

+1

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


All Articles