8/15/2023 0 Comments Java downcast upcast![]() ![]() If it doesn’t, a ClassCastException is thrown at runtime.ĭowncasting is useful when you want to access the specific methods and attributes of a subclass object that are not present in its superclass. If it does, the reference is converted to the subclass type. When downcasting is performed, the superclass reference is checked to see if it refers to an object of the subclass. This conversion is done explicitly by the programmer using the cast operator. In other words, it is a way of treating an object of a superclass as an object of its subclass. It is a process of converting a superclass reference type to its subclass object. Good to Read:- Easiest Way to Learn What Is Garbage Collection In Java Downcasting in Java and How Does It Work?ĭowncasting is the opposite of upcasting. MyAnimal.makeSound() // prints “Dog is barking” Now, myAnimal can only access the methods and attributes that are defined in the Animal class: We then upcast myDog to an Animal reference called myAnimal. In this code, we create a Dog object called myDog. Suppose we have a class hierarchy that looks like this: class Animalĭog myDog = new Dog() Animal myAnimal = myDog Let’s consider an example of upcasting in Java. ![]() This allows you to write more generic code that can handle different types of objects without having to write separate code for each type. Upcasting is useful when you want to use a single reference type to refer to objects of different subclasses. The resulting object can only access the methods and attributes that are defined in the superclass. When upcasting is performed, the subclass object loses its specific attributes and methods that are not present in its superclass. This conversion is done implicitly by the Java Virtual Machine (JVM) at runtime. In other words, it is a way of treating an object of a subclass as an object of its superclass. It is a process of converting a subclass object to its superclass reference type. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |