im a beginner and trying to understand that how to reference variables to object. i gave the codes bellow my question is is there anyone explain to me how ?
the cast would work if the reference "g" holds a reference to Soccer object. But plain casts without instanceof checks are prone to error.
moreover if you can work with out adding the casts then its recommended.
You need not apply a cast in cases if the subclass overrides the method in the superclass then at runtime the jvm will pick the subclass/overridden version to execute. but in cases where the subclass overloads the method in superclass you need a reference which is of type subclass to actually invoke the overloaded version. But if you have an instance of Game class and then try to cast it to Soccer class, the cast would fail.
The above explanation is based on my assumption that "g" is of type Game. but the example you have provided is not sufficient and moreover you havent stated you query clearly.
In the Game g = new Soccer(): the "g" reference refers to a Soccer instance. But the "g" reference is of type Game and hence it will not be able to see the overloaded methods in Soccer class as reference to method binding happens at compile time and hence at compile time "g" is a Game. So you will not be able to invoke the overloaded play() method of the Soccer class. You might question that the actual instance is of Soccer, but the actual instance type is considered only when the method being invoked are overridden by the subclass.
Now coming back to Soccer s = (Soccer) g- this would work because the actual object/instance referred to by "g" is of Soccer type. And you must be able to invoke the overloaded version of the play() method as well as the overridden version of the play method.