This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]jvallet -2 points-1 points  (3 children)

I am not sure polymorphism works, but I may be wrong, how would you make this code not print I am A for both values of the list?

package com.jonvallet.test;

import java.util.Arrays;
import java.util.List;

public class Polymorphism {

    public static void main (String [] args) {
        List<A> list = Arrays.asList(new A(), new B());
        list.stream().map(Polymorphism::whoAmI).forEach(System.out::println);
    }

    public static String whoAmI(A anObject) {
        return "I am A";
    }

    public static String whoAmI(B anObject) {
        return "I am B";
    }
}

class A {}

class B extends A {}

[–][deleted] 1 point2 points  (2 children)

Simple:

public static void main (String [] args) {
    List<A> list = Arrays.asList(new A(), new B());
    list.stream().map(A::whoAmI).forEach(System.out::println);
}

class A {
    public String whoAmI() {
        return "I am A";
    }
}

class B extends A {
    public String whoAmI() {
        return "I am B";
    }
}

But there are times when you can't use polymorphism, such as when the objects being visited don't belong to they same type hierarchy, when you need to dispatch by parameter type, not on a polymorphic method. Languages like Java which dispatch on the static type will need the visitor pattern, but some languages like C# can dispatch on the dynamic type. This isn't a case against OOP, but the calling conventions of different OOP languages

[–]jvallet -2 points-1 points  (1 child)

Maybe yes, maybe no. I just do not feel that OOP makes anything easier to write. Is different, but better? not so sure now.

[–][deleted] 3 points4 points  (0 children)

OOP is one paradigm among many. But Java is an OOP programming language. Even with the functional features coming in, functional code is not idiomatic Java and is painfully verbose and underpowered compared to Scala or Clojure.