G
G
gleendo2017-03-26 19:37:07
Java
gleendo, 2017-03-26 19:37:07

What is the advantage of super, specifically in this case (Generalizations)?

Why exactly in this example are super used in class methods I did not understand. As for me, even without super, everything also works. Explain what is the essence of the use in this example. Hierarchy of animal classes used for this example: Hierarchy of animal classesclass GenericReadAndWrite {}

public class App {
    public static void main(String[] args) {
        Generic1<Cat> g1 = new Generic1<>();

        GenericReadAndWrite.f1(g1, new Cat());
        GenericReadAndWrite.f1(g1, new Pet()); // Error

        // --------------------------------------------------

        Dog cat = GenericReadAndWrite.f2(new Generic2<Pug>());
    }
}


class Generic1<T> {
    public void set(T arg) {}

}

class Generic2<T> {
    public T get() {
        return null;
    }
}

class GenericReadAndWrite {
    static <T> void f1(Generic1<? super T> obj, T item) {
        obj.set(item);
    }

    static <T> T f2(Generic2<? extends T> obj) {
        return obj.get();
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dummyman, 2017-03-27
@dummyman

Well, look at the example of animals. If in the class of cats you define a method to feed someone, for example, a dog or a wolf, or a larger cat. Not?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question