/** * Type equivalence in Java. * There is not real notion of two type being the same in Java * You can define a class to inherit from another without any * change (as B does from B below) but they are not equivalent * * Java allows comparison of instances either view equals or == * BUT, when you get to function calls functions that expect B * will NOT accept A. * * @author gtowell * Created: July 2022 */ public class Equiv { /** * A very simple class */ private class A { int b; // Not really used, but I felt like it need to be there @Override public String toString() { return String.format("%s %d", this.getClass().getName(), b); } } /** * B extends A without change. * This does not create equivalent types */ private class B extends A { } /** * A function that expects something of type A. * B will also be allowed * @param aa */ public void accA(A aa) { } /** * A function that expects something of type B * A will not be allowed. * @param bb */ public void accB(B bb) { } /** * A little testing function */ public void test() { A a = new A(); B b = new B(); System.out.format("%s\n%s\n", a, b); System.out.println(a.equals(b)); System.out.println(a == b); accA(a); accA(b); accB(a); // Does not compile because of this line!! Explain!! accB(b); } public static void main(String[] args) { new Equiv().test(); } }