![]() ![]() For this, we will define two classes and try to downcast the object of super class with wrong syntax. The following example illustrates what could be the result of providing the wrong syntax of downcasting. If we do so the compiler will throw ‘ClassCastException’. Also, we can’t directly downcast objects like we are going to do in the next example. Syntax nameOfSubclass nameOfSubclassObject = (nameOfSubclass) nameOfSuperclassObject Īlthough this syntax seems so easy, many of us can do mistakes while writing this syntax. ![]() In this case, downcasting comes into the picture, it allows us to access the member variables and methods of sub class to super class. Here, the sub class contains a few features that its super class wants to use. Need for Downcastingįor an instance, assume that there are two classes, one is the super class and the other one is its sub class. ![]() On the other hand in the downcasting process, the original object does not get changed, only its type changed. in typecasting we work directly with values and if we change the value once, we cannot restore it. The first is that we can type cast only primitive datatypes and the second is that it is irreversible action i.e. However, there exist a few differences too. Object Downcasting in JavaĮarlier we discussed that downcasting is somewhat similar to typecasting. In this article, we will learn about downcasting and what are the rules that we must follow to downcast an object in Java. It is quite similar to what we do in primitive typecasting. We need to perform the conversion explicitly. This allows you to subsequentially check whether the result of the downcast is null or not. The as operator performs a downcast that evaluates to null rather than throwing an exception if the downcast fails. If you don’t want this behavior, you can use the as operator. In Java, downcasting is the process of converting an object of parent class to object of child class. If a downcast fails, it’ll throw an exception at runtime. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |