Essentially you shouldn’t do that. It’s a pity that in an artificial example it’s even worth doing and seems right.
If you want to do it anyway you should perform a cast to make the object type change:
class Main {
public static void main( String[] args ) {
ABC obj = new XYZ();
System.out.println(((XYZ) obj).getXYZ());
}
}
class ABC {
int x = 0;
public int getABC() {
return x;
}
}
class XYZ extends ABC {
int y = 0;
public int getXYZ() {
return y;
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
When you say an object is of a certain type the compiler only lets the code access the members of that type, so you only let the members of ABC
in this case. As the concrete object is XYZ
and has other members you could access them if the compiler let you. To make the compiler leave you have to say that you want to access this object by the concrete type and use the cast for that reason.
But if you do this, there’s probably something wrong with the modeling. If you want to access the concrete object, then why did you declare it an abstract object? When the declaration uses the supertype because it will only do operations on top of what the supertype allows, you are ensuring that you do not need members of the subtypes.
This can be done and in some cases may be useful, but it is still a conceptual error.
Even in a realistic concrete case (which goes beyond an exercise of an individual mechanism) it is not so simple to do so. In real code you will run the risk of having other subtypes of that type that do not contain the member you are using and your application will break, so you have to make sure that it is of the subtype you hope to be to ensure it works. Obviously in this example code does not need to do this, it is obvious that it is of the correct subtype, but this code does not exist in real applications. And if there is doing something very wrong, it makes no sense.
It is nice to learn the mechanism used, but if you do not know how to apply it correctly you will program wrong. Look for real code where this kind of mechanism can be really useful. In correct modeling it is almost never useful. Recently I I answered in another language where it was useful, even then it was not ideal and it would be better to have another solution.