[英]Does polymorphism apply on value objects?
Consider a scenario when a parent class only has attributes and "no method" and several child classes are extending the parent class for code re-usability. 考虑一种情况,当父类仅具有属性且没有方法,并且几个子类扩展了父类以实现代码可重用性时。
These objects are essentially value objects and if a child value object is passed in a method accepting the parent variable as input, will you still call it a polymorphic behavior when child has no behavior to override? 这些对象本质上是值对象,并且如果在接受父变量作为输入的方法中传递了子值对象,当子对象没有要覆盖的行为时,您是否仍将其称为多态行为? For example: 例如:
class Parent { int value = 100; /* doesn't have any method to be overriden */ }
class Child1 extends Parent {};
class Child2 extends Parent {};
public class Test {
public static void main(String[] args) {
Parent obj1 = new Child1();
doSomething(obj1);
Parent obj2 = new Child2();
doSomething(obj2);
Child1 obj3 = new Child1();
doSomething(obj3);
Child2 obj4 = new Child2();
doSomething(obj4);
}
static void doSomething(Parent p) {
// some code
}
}
Will you still call above a polymorphic behavior even though there is no behavior at all? 即使根本没有行为,您还会在多态行为之上调用吗?
Do you mean something like this? 你的意思是这样吗?
class A { int foobar = 42; }
class B extends A {}
public class Test3 {
public static void printAsFoobarValue(A a) { System.out.println(a.foobar); }
public static void printBsFoobarValue(B b) { System.out.println(b.foobar); }
public static void main(String[ ] args) throws Exception {
A a = new A();
B b = new B();
A c = new B();
printAsFoobarValue(a);
printAsFoobarValue(b);
printAsFoobarValue(c);
printBsFoobarValue(b);
}
}
I'll call this polymorph. 我将其称为多态。
由于您帖子中的Parent
类没有子类可以覆盖的方法,因此Test中的dosomething
方法执行的操作不会调用任何覆盖的方法-如果是这种情况,则不是多态性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.