I don't understand why this code works.
I have 3 classes: A, B and C.
Class A have class B as attribute. Class C extends class B. I can initialize class C and set is as attribute of class A.
public class A {
public B b;
public A(){}
}
public class B {
public String username;
public B(){}
}
public class C extends B {
public String password;
public C(){}
}
public class Program
{
public static void main(String[] args) {
A a = new A();
B b = new B();
C c = new C();
a.b = c;
}
}
How can Java cast B as C if C is "larger"? If I try to do it normally, you can't, for example:
public class Program
{
public static void main(String[] args) {
B b = new C();
// ERROR cannont find symbol (b.password)
b.password = "asd";
}
}
or I try it like this:
public class Program
{
public static void main(String[] args) {
B b = new B();
C c = new C();
b = c;
//ERROR cannont find symbol (b.password)
b.password = "123";
}
}
Actual problem I have is with HTTP response. I create my own response object that has context. This context can be ResponseContext or ResponseContextPagination that extends ResponseContext. So, my Response object has ResponseContext atribute, and I can set that atribute as ResponseContextPagination and when I return whole response to client, it has valid JSON:
{"context":{"hasMore":false,"isLoggedIn":false}}
So, I can't get hasMore attribute if I try to access it because ResponseContext does not have hasMore attribute but why can I then even set hasMore as ResponseContextPagination object? And it serializes fine into JSON.