Lets implement the Downcasting Objects on Eclipse IDE and find out whether we get any errors by following the below steps -ġ. Downcasting in Java - Yes, a variable can be downcast to its lower range substitute by casting. This statement wont throw compile time error but throws run time error. Downcasting statement throws run time error.Īnimal a = new Animal( ) //Object created for Animal ClassĬat c2 = (Cat)a //Downcasting. This statement wont throw any errors.Įxample2 - No Case - This Program wont throw compiler error but throws run time error. Dowcasting statement wont throw any errors.Īnimal a = null //Object a is just define as Animal Class type here but not created.Ĭat c2 = (Cat) a //Downcasting. Lets see the below examples to find out the cases -Įxample1 - Yes Case - This Program can be Run without any compiler and run time errors. The answer is No, when you create Super Class 'Animal' object. The answer is Yes, when you just define the Super Class 'Animal' object instead of creating it. Hence Downcasting need to be done manually to avoid this problem.Īfter Downcasting, can you run the program sucessfully ? What you can do is the following codeList list2 list.stream().Java doesn't have a way of automagically doing this for you. But if you have a group of different animals and cast them all to a Cat, then there are some chances that some of the animals are actually dogs and the process fails. Answer: You need to create a list of the new objects, which mean converting each of old objects. Why Upcasting is automatical and Downcasting need to be done manually ?Ĭonverting a Cat or Dog to Animal can never fail, hence the Upcasting is done automatically. Consider the following code that upcasts and downcasts variables. Assigning Super Class Object reference to Sub Class Object reference) cannot be done automatically by Java, but we need to do it manually by following the below syntax -Īssuming that Animal Class is the super Class of the Cat Class -Ĭat c1 = new Cat( ) //Creating Object for Cat ClassĪnimal a = c1 //Automatic Upcasting to AnimalĬat c2 = (Cat) a //manually Downcasting back to a Cat Assigning Sub Class Object reference to Super Class Object reference) can be automatically done by Java.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |