public class NewMain { public void myMethod(String s)
{
System.out.println("My String");
} public void myMethod(StringBuffer sb)
{
System.out.println("My StringBuffer");
} public static void main(String args[])
{
NewMain t = new NewMain();
t.myMethod(null);
}
}
对 myMethod 的引用不明确,test2.NewMain 中的 方法 myMethod(java.lang.String) 和 test2.NewMain 中的 方法 myMethod(java.lang.StringBuffer) 都匹配
t.myMethod(null); 但是若是一个String 与 Object 的方法(将StringBuffer改为Object), 则会调用的string方法.
{
System.out.println("My String");
} public void myMethod(StringBuffer sb)
{
System.out.println("My StringBuffer");
} public static void main(String args[])
{
NewMain t = new NewMain();
t.myMethod(null);
}
}
对 myMethod 的引用不明确,test2.NewMain 中的 方法 myMethod(java.lang.String) 和 test2.NewMain 中的 方法 myMethod(java.lang.StringBuffer) 都匹配
t.myMethod(null); 但是若是一个String 与 Object 的方法(将StringBuffer改为Object), 则会调用的string方法.
public void myMethod(StringBuffer sb)
{
System.out.println("My StringBuffer"); //这儿是输出"My StringBuffer"这个字符串,参数根本就没有使用.所以不管你的参数是什么,都没有关系,结果是一样的.
}关于null,它就是空的意思,就相当于一个开关,如果它没有接任何电器,它就是null.
}
t.myMethod(null);
之间做个是否为null的判断,根据判断你爱怎么做就怎么做,像
if(null == null){
t.myMethod(String);
}
else{
t.myMethod(StringBuffer);
}
t.myMethod(null);
之前做个是否为null的判断,根据判断你爱怎么做就怎么做,像
if(null == value){
t.myMethod(String);
}
else{
t.myMethod(StringBuffer);
}
{
System.out.println( "My String ");
} public void myMethod(Object sb)
{
System.out.println( "My StringBuffer ");
} public static void main(String args[])
{
NewMain t = new NewMain();
t.myMethod(null);
}
}
如果这样的话是输出MY STRING 调用的方法是OBJECT的子类(最小的子类)如果不改。STRING和STRINGBUFFER同时都继承自OBJDECT(他们是平辈儿),则编译报错。
提供几个例子便于理解://1.
class EasyOver {
static void go(int x) { System.out.print("int "); }
static void go(long x) { System.out.print("long "); }
static void go(double x) { System.out.print("double "); } public static void main(String [] args) {
byte b = 5;
short s = 5;
long 1 = 5;
float f = 5. Of; go(b);
go(s);
go(l);
go(f);
}
}//Which produces the output://int int long double2.class AddBoxing {
static void go(Integer x) { System.out.println("Integer"); }
static void go(long x) { System.out.println("long"); } public static void main(String [] args) {
int i = 5;
go(i); // which go() will be invoked?
}
}//Which produces the output://long3.class AddVarargs {
static void go(int x, int y) { System.out.println("int,int");}
static void go(byte... x) { System.out.println("byte ... "); }
public static void main(String[] args) {
byte b = 5;
go(b,b); // which go() will be invoked?
}
}
//the output is//int,int4.class BoxOrVararg {
static void go(Byte x, Byte y)
{ System.out.println("Byte, Byte"); }
static void go(byte... x) { System.out.println("byte... "); } public static void main(String [] args) {
byte b = 5;
go(b,b); // which go() will be invoked?
}
}//As it turns out, the output is//Byte, Byte