Exploring the Super Keyword and Casting Techniques
Mastering Super keyword, Upcasting and Downcasting
Everything You Need to Know ☝
Super keyword
The super keyword is used to call the constructor of a
superclass from a subclass. That is, it
allows access to the members (methods, fields, constructors) of the parent
class from within the subclass. Variables and methods can be called at any time
via the super keyword. Unless one explicitly invokes the variables or methods of
the super class using the super keyword, then nothing happens.
Uses of super keyword
Casting
The term “Type
casting” specifically used when referring to casting objects from one class
type to another, typically in the context of inheritance and polymorphism. There
are two types of objects, parent object and child object.
“Type casting” and “casting” refer to the same fundamental concept of converting values from one data type to another. Upcasting and Downcasting is the type of object typecasting.
Upcasting
The process
of assigning an object from the sub class to a variable in the super class
reference is called upcasting. The class that creates the object always runs
with the object.
Downcasting
Dawncasting means turning the sub class object (subclass constructor) assigned to the variable from the super class reference into a sub class variable again. Dawncasting can only be done by upcasting.
Difference between Upcasting and Downcasting💁
Why we need Upcasting and Downcasting ❔
Upcasting📌
👉Upcasting
allows for polymorphic behavior , where objects of different subclasses can be
treated uniformly through their common superclass interface.
👉 Upcasting enables programmers to
focus on the common behavior and attributes of objects, rather than their
specific implementations.
👉By upcasting objects to their
superclass types, you can write methods and functions that operate on the
superclass, making your code more flexible and adaptable to changes in
requirements.
Downcasting📌
👉Accessing
Subclass-Specific Behaviour
👉Downcasting is useful when you need
to perform operations or manipulations that are specific to a subclass but not
applicable to the superclass.
👉Avoiding Type Errors
Reference-:
W3Schools Online Web
Tutorials
E-Mail-:rasanjaliherath899@gmail.com
Comments
Post a Comment