【问题标题】:Method Overloading solution方法重载解决方案
【发布时间】:2014-08-30 08:29:19
【问题描述】:

如果B 类扩展A 类:以下代码的输出是什么?

 package com.swquiz.overloading;
public class TitBitOverloading7 {
    public static void main(String[] args) {
        overload((A)null);
        overload((B)null);
    }
    public static void overload(A a) {
        System.out.println("A");
    }
    public static void overload(B b) {
        System.out.println("B");
    }
}

Ans - A B 我不知道怎么办?你能解释一下如何处理 null 吗?

【问题讨论】:

  • Java 是按值传递,但为对象传递的值是对象引用。您首先使用 A 的引用调用该方法,然后再使用 B 的引用来调用该方法的事实是导致您的行为的原因。对象值都是 null,但引用值是 A 和 B,引用是传递的内容。请参阅this post 进行深入讨论。

标签: java oop inheritance overloading


【解决方案1】:
show_int(int x){
  print("int "+x.toString());
}
show_double(double x){
  print("double "+x.toString());
}

show_value(var x){
  if (x.runtimeType == int){
    show_int(x);
  }else if (x.runtimeType == double){
    show_double(x);
  }else {
    throw ("Not implemented");
  }
  
}

void main() {
  
  int x = 5;
  show_value(x);
    double y = 5.5;
  show_value(y);
     String m = "5.5";
  show_value(m);
}

【讨论】:

    【解决方案2】:

    您可以将 null 转换为任何引用类型而不会出现任何异常。

    输出将是

    A
    B
    

    原因,方法调用时会考虑发送的对象类型。由于您分别具有 A 和 B 的类型转换,因此将调用的方法由运行时传递的参数的类型标识(多态性)

    null 是您将传递给特定方法的参考值。

    【讨论】: