简体   繁体   English

方法重载的Java编译错误

[英]Java Compilation Error with Method overloading

What would be the best way to achieve testCall2 below without doing explicit parsing (Sub1) in ? 在不进行显式解析(Sub1)的情况下实现以下testCall2的最佳方法是什么?

class Super {
}

class Sub1 extends Super {
}

class Sub2 extends Super {
}

public void testCall2(Super in) {
    testCall(in);        // <~~~ Compilation Error 

}

public void testCall(Sub1 sub) {

}

public void testCall(Sub2 sub) {

}

You'd have to refactor and use polymorphism. 您必须重构并使用多态。 Declare the testCall method in Super Super声明testCall方法

class Super {
    public void testCall() {}
}

and implement it in the subclasses. 并在子类中实现它。

Then invoke it 然后调用它

public void testCall2(Super in) {
    in.testCall(); 
}

Otherwise you'll have to use a cast to transform the value's type to a type expected by either of the methods. 否则,您将不得不使用强制类型转换将值的类型转换为两种方法所期望的类型。

Obviously it will give compile time error because you are creating methods out of class body. 显然,这将导致编译时错误,因为您是在类主体之外创建方法。 your all methods are out of class body.. 您的所有方法都超出类的范围。

class Super {
}

class Sub1 extends Super {
}

class Sub2 extends Super {
}// your all three classes are started and ended immediately

public void testCall2(Super in) {
    testCall(in);        // <~~~ Compilation Error 

}

public void testCall(Sub1 sub) {

}

public void testCall(Sub2 sub) {

}
//and all three methods are defined out of any  class body.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM