黑马程序员技术交流社区

标题: 没有想到的重载参数问题 [打印本页]

作者: 小黑马    时间: 2012-9-4 11:18
标题: 没有想到的重载参数问题
本帖最后由 马小龙 于 2012-9-4 13:50 编辑
  1. package com.itheima;
  2. public class Test3 {  
  3.    
  4.     public void myMethod(String str) {  
  5.         System.err.println("string");  
  6.     }  
  7.       
  8.     public void myMethod(Object obj) {  
  9.         System.err.println("object");  
  10.     }  
  11.       
  12.     public static void main(String[] args) {  
  13.         Test3 t = new Test3();  
  14.         t.myMethod( null );  //传入参数null
  15.     }  
  16. }  
复制代码
这里我在方法中传入null,为什么会找 public void myMethod(String str) 这个方法?
作者: 黑马--张帅    时间: 2012-9-4 11:34
01.package com.itheima;

02.public class Test3 {  

03.   
        int  a = 3;
04.    public void myMethod(String str) {  

05.        System.err.println("string");  

06.    }  

07.      

08.    public void myMethod(Object obj) {  

09.        System.err.println("object");  

10.    }  

11.      

12.    public static void main(String[] args) {  

13.        Test3 t = new Test3();  

14.        t.myMethod( null );  //传入参数null
            t.myMethod( "abc" );

15.    }  

16.}  
   加上  t.myMethod( "abc" ); 依然执行的是mymethod(String str)因为String类继承Object
传入的是具体的字符串类型就会执行mymethod(String str),又因为String是集合类是引用类型,默认的对象类型是null,所以还是执行mymethod(String str)如果你这样调用的话 t.myMethod( a ); 执行的就是public void myMethod(Object obj)
作者: 杨习平    时间: 2012-9-4 11:40
01.package com.itheima;

02.public class Test3 {  

03.   

04.    public void myMethod(String str) {  

05.        System.err.println("string");  

06.    }  

07.      

08.    public void myMethod(Object obj) {  

09.        System.err.println("object");  

10.    }  

11.      

12.    public static void main(String[] args) {  

13.        Test3 t = new Test3();  

14.        t.myMethod( null );  //传入参数null

15.    }  

16.}  
上面的代码中,你在一个类中定义了两个方法,一个是传字符串,另一个是Object  是所有类的超类,
所以String是Object的子类,当然在重载方法的时候是看传入参数的类型,而String的默认值是  null  ,
Object 是很多种类型的泛型,所以只有调用具体的 public void myMethod(String str) 这个方法。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2