Posts

Showing posts with the label inheritance

How can the Object class be a super class of subclasses?

Fact 1: Java does not support multiple inheritance. Fact 2: Object is a superclass of all other classes If I have a class Parent and a class Child which is inheriting the class Parent: class Parent { } class Child extends Parent { } In this case, how will the class Child inherit the Object class, if Java does not support multiple inheritance? How is the relationship between these three defined? Option 1: Option 2: It's Option 2. If you define a superclass, that will be the immediate superclass of your class. If you don't define one, Object will be the immediate superclass. class Parent { } class Child extends Parent { } is equivalent to class Parent extends Object { } class Child extends Parent { } So, while Object is the superclass of all classes, there might be some steps in the class hierarchy before you get to Object. It's not the immediate superclass of all classes. Object might not be a direct parent, but it's always a super parent. Child extends Par...

What is a real life example of generic

I understand that <? super T> represents any super class of T (parent class of T of any level). But I really struggle to imagine any real life example for this generic bound wildcard. I understand what <? super T> means and I have seen this method: public class Collections { public static <T> void copy(List<? super T> dest, List<? extends T> src) { for (int i = 0; i < src.size(); i++) dest.set(i, src.get(i)); } } I am looking for an example of real life use case where this construction can be used and not for an explanation of what it is. The easiest example I can think of is: public static <T extends Comparable<? super T>> void sort(List<T> list) { list.sort(null); } taken from the same Collections. This way a Dog can implement Comparable<Animal> and if Animal already implements that, Dog does not have to do anything. EDIT for a real example: After some email ping-pongs, I am allowed to present a real e...