简体   繁体   中英

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方法执行的操作不会调用任何覆盖的方法-如果是这种情况,则不是多态性

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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