Posts

Showing posts from April, 2023

Polymorphism

Image
  Polymorphism After overriding a super class method in a sub class, casting and running the super class method through the super class reference is polymorphism. Simply put, the process of calling the sub class method from the super class reference using the 3 concepts of overriding, inheritance, and casting can be described as polymorphism. Figure 1 : Polymorphism Example As shown in this simple example, the subclass method is called by both upcasting and downcasting. Figure 2 : Polymorphism Example This code creates an " Employee " superclass and two subclasses, " Manager " and " Programmer ". The " Employee " superclass has a single method called " work " that simply prints out "The employee works". Both " Manager " and " Programmer " are subclasses of " Employee " and they override the " work " method with their respective tasks. The " Manager " subclass has an additional

Casting

Image
Casting Upcasting In upcasting, we cannot access from bottom level to top level, but we can access from top level to bottom level. Upcasting is used to convert an object, method or variable of the super class to an object, method or variable of the sub class. Upcasting simply means giving a sub class object to a super class variable. Figure 1: Up casting Example In inheritance, the things in the super class are also owned by the sub class. Therefore, the constructor of the super class also runs in the sub class. So the sub class can access the constructor of the super class. Also, the constructor is called when the object is created. Therefore, when the object of the super class is created, the constructor of the super class is called. Since the sub class can access the constructor of the super class, the sub class can be accessed at the time of creating the object of the super class. Downcasting Turning the sub class object into a super class variable back into a sub class object is d