I'm confused about what it means to cast objects in Java.
Say you have...
Superclass variable = new Subclass object();
(Superclass variable).method();
What is happening here? Does the variable type change, or is it the object within the variable that changes? Very confused.
The example you are referring to is called Upcasting in java.
It creates a subclass object with a super class variable pointing to it.
The variable does not change, it is still the variable of the super class but it is pointing to the object of subclass.
For example lets say you have two classes Machine and Camera ; Camera is a subclass of Machine
If you execute the above statements it will create an instance of Camera class with a reference of Machine class pointing to it.So, now the output will be "Camera Started" The variable is still a reference of Machine class. If you attempt
machine1.snap();
the code will not compileThe takeaway here is all Cameras are Machines since Camera is a subclass of Machine but all Machines are not Cameras. So you can create an object of subclass and point it to a super class refrence but you cannot ask the super class reference to do all the functions of a subclass object( In our example
machine1.snap()
wont compile). The superclass reference has access to only the functions known to the superclass (In our examplemachine1.start()
). You can not ask a machine reference to take a snap. :)Superclass variable = new subclass object();
This just creates an object of type subclass, but assigns it to the type superclass. All the subclasses' data is created etc, but the variable cannot access the subclasses data/functions. In other words, you cannot call any methods or access data specific to the subclass, you can only access the superclasses stuff.
However, you can cast Superclassvariable to the Subclass and use its methods/data.
Have a look at this sample:
in some cases we can’t provide guarantee for the type of elements or objects present inside our collection or wise, at the time of retrieval compulsory we should perform type casting otherwise we will get compile time error.
Arrays are always type safe that is we can provide the guarantee for the type of elements present inside array. to achieve type safety we have to use typecasting.
Lets say you have Class A as superclass and Class B subclass of A.
Casting is necessary to tell that you are calling a child and not a parent method. So it's ever downward. However if the method is already defined in the parent class and overriden in the child class, you don't any cast. Here an example:
The two method call will both print : "this is the child".