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 |