The super keyword in Java is a reference variable that is used to reference the nearest superclass object. Whenever you create an instance of a subclass, an instance of the super class is created implicitly, referenced by the super variable.
How to use super keyword in Java
- super is used to reference the instance variable of the latest superclass.
- super () is used to summon the Constructor of the latest superclass.
- super is used to summon the method of the nearest superclass.
In the next section, we'll look at each of how to uses super keyword in Java with detail example.
super is to reference the instance variable of the latest superclass
The problem occurs without the super keyword:
In the example above, both the Vehicle and Bike classes share the same speed attribute. The instance variable of the current class is referenced by default, but you must reference the instance variable of the superclass, and that is why we use the super keyword to distinguish between instance variables of the superclass and variables. instance of the current class.
Dealing with super keyword in Java:
super () is used to summon the Constructor of the latest superclass
You follow this example:
Note: super () is automatically added to each Constructor of the class by the compiler.
Over the previous chapters, we learned that the default constructor is provided by the compiler, but it also adds super () to the first command. If you are creating your own constructor and you do not have this () or super () as the first command, then the compiler will provide super () as the first command for that constructor.
Another example of how to use super keyword, in java with detail example. In this example super () is provided by the compiler.
super is used to summon the method of the nearest superclass
The super keyword can also be used to summon the nearest superclass method. It should be used in subclasses that contain the same method as the superclass, as in the following example:
In the above example, both the Student and Person class have the same message () method. If we call the message () method from the Student class, it calls the message () method of the Student class, not the Person class. because of local privileges.
In a situation where no method of subclass is like the superclass, no super keyword is used. In the example below, the message () method is summoned from the Student class, but the Student class does not have this message () method, so you can directly call the message () method.
Example program does not need super keyword:
To find out more about object oriented programming concept (oop):
Comments
Post a Comment