简体   繁体   中英

Calling the parent class constructor and super variable in inheritance java

I have a question about the super variable in java. I understand that it is used to call the parent class constructor from the child class and access methods of the parent class but I have a couple of questions about this. Firstly I was always under the impression that when a method or constructor was called then we had to send arguments that were stored in the parameters of the constructor or method. When we call the method using the Super constructor we just send the variables which have not been initialized. Secondly I looked up the definition of the Super variable and found this : 'The super keyword in java is a reference variable which is used to refer immediate parent class object.' What exactly does this mean?

Though, your question does not seems to be much clear but i believe that you are confused with super keyword .

Take a look at the below lines i had written for the usage of super keyword.

Let's say a class Father has one default constructor and three methods (non static method A, non static method B and static method C). Class Son extends the class Father and overrides method A of Father. Father and son shares inheritance relationship.

  1. Now, without creating the object of father, if Son wants to use the constructor of Father then it can be used by writting “ super() ” as the first statement inside the constructor of Son. The constructor call must be done inside the constructor of child only.
  2. Son has overridden a method A of Father but still want to use the father's implementation of the same method. This can be done by using the “super.methodName()” without creating father's object . Though, it can also be done by creating the father's object in main method.
  3. Son can use the method which it does not override (method B of father class) without creating father's object by super keyword only inside any non-static method. Though, you can also simply create father's object in son class and use it.
  4. For accessing the static method of father inside son (obviously not overridden, as you cannot override static methods), we can use object of both, father and son.

So, if you can read definition of super keyword and read the examples i have given for the usage of super keyword then i hope it should be clear.

Though, if you still unclear about any scenario then please feel free to comment them down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM