0

If class B extends class A: what is the output of the following code?

 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 I don't know how? Can you explain how null is processed.

Filex
  • 100
  • 9
PsYcHeD
  • 13
  • 2
  • 1
    Java is pass-by-value, but the value passed for objects is the object reference. The fact that you first call the method with a reference of A then a reference of B is what's causing your behaviour. The object values are both null, but the reference values are A and B and the references are what is passed. See [this post](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) for an in depth discussion. – Dan Temple Jul 09 '14 at 10:48

2 Answers2

1

You can cast null to any reference type without getting any exception.

Output will be

A
B

Reason, the type of object sent will be considered during method call. Since you have a type cast of A and B respectively, the method which will be called be identified by the Type of the argument being passed at runtime ( polymorphism )

null is the reference value you will be passing to a particular method.

vinayknl
  • 1,242
  • 8
  • 18
0
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);
}