就Java而言,当有人问:
什么是多态?
将超载或重载是一个可以接受的答案?
我认为还有更多的东西.
如果您有一个抽象基类定义了一个没有实现的方法,并且您在子类中定义了该方法,那还是会覆盖吗?
我认为超载肯定不是正确的答案.
如何以易于理解的方式描述多态?
我们可以在Internet和书籍上找到关于该主题的大量信息,例如Type polymorphism.但是,让我们尽可能地让它变得简单.
请参阅以下示例:
interface I {}
class A implements I {}
class B implements I {}
class Foo{
void f(A a) {}
void f(B b) {}
static public void main(String[]args ) {
I[] elements = new I[] {new A(), new B(), new B(), new A()};
Foo o = new Foo();
for (I element:elements)
o.f(element);//won't compile
}
}
Run Code Online (Sandbox Code Playgroud)
为什么重载方法不支持向上转换?
如果在运行时实现了重载,它将提供更大的灵活性.例如,访客模式会更简单.是否存在阻止Java执行此操作的任何技术原因?
现在在本页(http://landoflisp.com)上阅读Lisp,我在页面上的第二个段落中找到了以下语句,单击链接CLOS GUILD时显示:
关于该示例的重要注意事项是,为了确定在给定情况下调用哪种混合方法,CLOS需要考虑传递给该方法的两个对象.它基于多个对象的类型调度到该方法的特定实现.这是传统的面向对象语言(如Java或C++)中不可用的功能.
这是示例Lisp代码:
(defclass color () ())
(defclass red (color) ())
(defclass blue (color) ())
(defclass yellow (color) ())
(defmethod mix ((c1 color) (c2 color))
"I don't know what color that makes")
(defmethod mix ((c1 blue) (c2 yellow))
"you made green!")
(defmethod mix ((c1 yellow) (c2 red))
"you made orange!")
Run Code Online (Sandbox Code Playgroud)
不,我认为最后一句话是错的.我实际上可以使用以下Java代码完成此操作:
public class Main {
public static void main(String[] args) {
mix(new Red(), new Blue());
mix(new Yellow(), new Red());
}
public …Run Code Online (Sandbox Code Playgroud) 我有一个String,可以是Double或Integer类型或其他类型.我首先需要创建一个Double或Integer对象,然后将其发送到重载方法.到目前为止,这是我的代码;
public void doStuff1(object obj, String dataType){
if ("Double".equalsIgnoreCase(dataType)) {
doStuff2(Double.valueOf(obj.toString()));
} else if ("Integer".equalsIgnoreCase(dataType)) {
doStuff2(Integer.valueOf(obj.toString()));
}
}
public void doStuff2(double d1){
//do some double related stuff here
}
public void doStuff2(int d1){
//do some int related stuff here
}
Run Code Online (Sandbox Code Playgroud)
我想在没有if/else的情况下这样做,就像这样;
Class<?> theClass = Class.forName(dataType);
Run Code Online (Sandbox Code Playgroud)
问题是'theClass'仍然无法转换为double或int.我会感激任何想法.谢谢.
找到一个相关的线程; 在Java中重载和多次调度
java ×4
overloading ×3
oop ×2
polymorphism ×2
class ×1
clos ×1
lisp ×1
overriding ×1
reflection ×1