我添加了三个带参数的方法:
public static void doSomething(Object obj) {
System.out.println("Object called");
}
public static void doSomething(char[] obj) {
System.out.println("Array called");
}
public static void doSomething(Integer obj) {
System.out.println("Integer called");
}
Run Code Online (Sandbox Code Playgroud)
当我调用时doSomething(null),编译器会将错误视为模糊方法.所以是问题,因为Integer和char[]方法,或Integer和Object方法呢?
如果我用Java写这行:
JOptionPane.showInputDialog(null, "Write something");
Run Code Online (Sandbox Code Playgroud)
将调用哪种方法?
showInputDialog(Component parent, Object message)showInputDialog(Object message, Object initialSelectionValue)我可以测试一下.但在其他类似的情况下,我想知道会发生什么.
public class Test1 {
public static void main(String[] args) {
Test1 test1 = new Test1();
test1.testMethod(null);
}
public void testMethod(String s){
System.out.println("Inside String Method");
}
public void testMethod(Object o){
System.out.println("Inside Object Method");
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试运行给定的代码时,我得到以下输出:
内部字符串方法
任何人都可以解释为什么带有String类型参数的方法被调用?
OUTPUT:乙
为什么虚拟机会调用此方法f(null){System.out.println("B");}?
为什么不 f(null){System.out.println("A");}
public class Test{
public static class A {}
public static class B extends A {}
public void f(A a) {System.out.println("A");}
public void f(B a) {System.out.println("B");}
public static void main(String[] args) {
new Test().f(null);
}
}
Run Code Online (Sandbox Code Playgroud) 我有以下代码
public class HelloWorld {
public void printData (Test t) {
System.out.println("Reached 1");
}
public void printData(NewTest t) {
System.out.println("Reached 2");
}
public static void main(String args[]) {
HelloWorld h = new HelloWorld();
h.printData(null);
}
}
Run Code Online (Sandbox Code Playgroud)
我有两个简单的课程
class Test {
}
class NewTest extends Test {
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出是 达到2
为什么第二个功能被选中执行而不是第一个?此外,当我通过使另一个类NewTest2扩展Test和类似的printData()函数尝试相同的代码时,它给了我编译时错误.是否有任何规则选择必须执行哪个功能以及何时执行?
java ×5
overloading ×3
null ×2
oop ×2
invocation ×1
jvm ×1
methods ×1
parameters ×1
polymorphism ×1