有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java异常、算术异常和对象

当我运行下面的代码时,它给出了输出“算术异常”。由于算术异常是检查异常,因此它的优先级高于未检查异常。 但它如何区分对象异常和算术异常呢

public class Solution {


public static void a(Exception e)
{
    System.out.println("Exception");

}
public static void a(ArithmeticException ae)
{
    System.out.println("ArithmeticException");
}

public static void a(Object o)
{
    System.out.println("Object");
}

public static void main(String[] args)
{
    a(null);
}

}


共 (2) 个答案

  1. # 1 楼答案

    重载方法时,将选择最具体的方法。在你的情况下,选择的顺序是

    Arithmetic Exception > Exception > Object
    

    根据^{}大多数特定方法在运行时选择

    If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

    Arithmetic ExceptionException更具特异性,后者比Object更具特异性

  2. # 2 楼答案

    在方法重载的情况下,Java语言将选择最具体的匹配,参数通过继承相互关联

    我们将用一个例子来演示这种行为

        public static void main(String[] args) {
            a(new Exception("some exception"));
            a(new ArithmeticException("something went wrong with numbers."));
            a(new String("hello world"));
            a(null);
        }
    

    产出如预期: enter image description here