Skip to content

Instantly share code, notes, and snippets.

@shankarnakai
Created January 7, 2025 19:56
Show Gist options
  • Save shankarnakai/8b99864dbcf78b190bbf87f792cc02e2 to your computer and use it in GitHub Desktop.
Save shankarnakai/8b99864dbcf78b190bbf87f792cc02e2 to your computer and use it in GitHub Desktop.
Exercising Covariance
import java.util.ArrayList;
import java.util.List;
public class CovarianceExample {
public static class Father {
int x = 5;
public Father(int x) {
this.x = x;
}
}
public static class Children extends Father {
int newProperty = 5;
public Children(int x, int newProperty) {
super(x);
this.newProperty = newProperty;
}
}
public static class Wrapper<T extends Father> {
private List<T> catalog;
@SafeVarargs
public Wrapper(T... values) {
this.catalog = new ArrayList<>();
for (T v : values) {
this.catalog.add(v);
}
}
public List<T> getCatalog() {
return this.catalog;
}
}
public static void format(String s, Object... args) {
System.out.println(String.format(s, args));
}
public static void printFather(List<Father> l) {
for (Father f : l ) {
format("**************************************************");
format("Father Value for X: %d", f.x);
format("**************************************************");
}
}
public static void printChildren(List<Children> l) {
for (Children c : l ) {
format("**************************************************");
format("Children Value for X: %d", c.x);
format("Children Value for NewProperty: %d", c.newProperty);
format("**************************************************");
}
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Wrapper<Father> wf = new Wrapper<>(
new Father(1),
new Father(10)
);
Wrapper<Children> wc = new Wrapper<>(
new Children(1, 2),
new Children(10, 20)
);
format("-------------------------------------");
format(" FATHER ");
format("-------------------------------------");
printFather(wf.getCatalog());
format("\n\n\n");
format("-------------------------------------");
format(" CHILDREN ");
format("-------------------------------------");
printFather((List<Father>) (List<?>) wc.getCatalog());
format("-------------------------------------");
printChildren(wc.getCatalog());
format("-------------------------------------");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment