Super is used in java

Super keyword in java with example

The super keyword refers to the objects of immediate parent class. Before learning super keyword you must have the knowledge of inheritance in Java so that you can understand the examples given in this guide.

The use of super keyword

1) To access the data members of parent class when both parent and child class have member with same name
2) To explicitly call the no-arg and parameterized constructor of parent class
3) To access the method of parent class when child class has overridden that method.

Now lets discuss them in detail with the help of examples:

1) How to use super keyword to access the variables of parent class

When you have a variable in child class which is already present in the parent class then in order to access the variable of parent class, you need to use the super keyword.

Lets take an example to understand this: In the following program, we have a data member num declared in the child class, the member with the same name is already present in the parent class. There is no way you can access the num variable of parent class without using super keyword. .

//Parent class or Superclass or base class class Superclass < int num = 100; >//Child class or subclass or derived class class Subclass extends Superclass < /* The same variable num is declared in the Subclass * which is already present in the Superclass */ int num = 110; void printNumber()< System.out.println(num); >public static void main(String args[]) < Subclass obj= new Subclass(); obj.printNumber(); >>

Accessing the num variable of parent class:
By calling a variable like this, we can access the variable of parent class if both the classes (parent and child) have same variable.

Let’s take the same example that we have seen above, this time in print statement we are passing super.num instead of num.

class Superclass < int num = 100; >class Subclass extends Superclass < int num = 110; void printNumber()< /* Note that instead of writing num we are * writing super.num in the print statement * this refers to the num variable of Superclass */ System.out.println(super.num); >public static void main(String args[]) < Subclass obj= new Subclass(); obj.printNumber(); >>

Output:
100
As you can see by using super.num we accessed the num variable of parent class.

2) Use of super keyword to invoke constructor of parent class

When we create the object of sub class, the new keyword invokes the constructor of child class, which implicitly invokes the constructor of parent class. So the order to execution when we create the object of child class is: parent class constructor is executed first and then the child class constructor is executed. It happens because compiler itself adds super()(this invokes the no-arg constructor of parent class) as the first statement in the constructor of child class.

Let’s see an example to understand what I have explained above:

class Parentclass < Parentclass()< System.out.println("Constructor of parent class"); >> class Subclass extends Parentclass < Subclass()< /* Compile implicitly adds super() here as the * first statement of this constructor. */ System.out.println("Constructor of child class"); >Subclass(int num) < /* Even though it is a parameterized constructor. * The compiler still adds the no-arg super() here */ System.out.println("arg constructor of child class"); >void display() < System.out.println("Hello!"); >public static void main(String args[]) < /* Creating object using default constructor. This * will invoke child class constructor, which will * invoke parent class constructor */ Subclass obj= new Subclass(); //Calling sub class method obj.display(); /* Creating second object using arg constructor * it will invoke arg constructor of child class which will * invoke no-arg constructor of parent class automatically */ Subclass obj2= new Subclass(10); obj2.display(); >>
Constructor of parent class Constructor of child class Hello! Constructor of parent class arg constructor of child class Hello!

Parameterized super() call to invoke parameterized constructor of parent class

We can call super() explicitly in the constructor of child class, but it would not make any sense because it would be redundant. It’s like explicitly doing something which would be implicitly done otherwise.
However when we have a constructor in parent class that takes arguments then we can use parameterized super, like super(100); to invoke parameterized constructor of parent class from the constructor of child class.
Let’s see an example to understand this:

class Parentclass < //no-arg constructor Parentclass()< System.out.println("no-arg constructor of parent class"); >//arg or parameterized constructor Parentclass(String str) < System.out.println("parameterized constructor of parent class"); >> class Subclass extends Parentclass < Subclass()< /* super() must be added to the first statement of constructor * otherwise you will get a compilation error. Another important * point to note is that when we explicitly use super in constructor * the compiler doesn't invoke the parent constructor automatically. */ super("Hahaha"); System.out.println("Constructor of child class"); >void display() < System.out.println("Hello"); >public static void main(String args[]) < Subclass obj= new Subclass(); obj.display(); >>
parameterized constructor of parent class Constructor of child class Hello

There are few important points to note in this example:
1) super()(or parameterized super must be the first statement in constructor otherwise you will get the compilation error: “Constructor call must be the first statement in a constructor”
2) When we explicitly placed super in the constructor, the java compiler didn’t call the default no-arg constructor of parent class.

Читайте также:  Php script error check

3) How to use super keyword in case of method overriding

When a child class declares a same method which is already present in the parent class then this is called method overriding. We will learn method overriding in the next tutorials of this series. For now you just need to remember this: When a child class overrides a method of parent class, then the call to the method from child class object always call the child class version of the method. However by using super keyword like this: super.method_name you can call the method of parent class (the method which is overridden). In case of method overriding, these terminologies are used: Overridden method: The method of parent class Overriding method: The method of child class Lets take an example to understand this concept:

class Parentclass < //Overridden method void display()< System.out.println("Parent class method"); >> class Subclass extends Parentclass < //Overriding method void display()< System.out.println("Child class method"); >void printMsg() < //This would call Overriding method display(); //This would call Overridden method super.display(); >public static void main(String args[]) < Subclass obj= new Subclass(); obj.printMsg(); >>
Child class method Parent class method

What if the child class is not overriding any method: No need of super

When child class doesn’t override the parent class method then we don’t need to use the super keyword to call the parent class method. This is because in this case we have only one version of each method and child class has access to the parent class methods so we can directly call the methods of parent class without using super.

class Parentclass < void display()< System.out.println("Parent class method"); >> class Subclass extends Parentclass < void printMsg()< /* This would call method of parent class, * no need to use super keyword because no other * method with the same name is present in this class */ display(); >public static void main(String args[]) < Subclass obj= new Subclass(); obj.printMsg(); >>

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

Hi,
I am new to the Java world and will truly appreciate if someone could help and guide me with the error and getting in the program below – public class A public void f1() System.out.println(“A—>f1”);>> public class B extends A public void f1() System.out.println(“B—->f1”);>> public class Test public static void main(String[] args) A b = new B();
B a1 = new A();
b.f1();
a1.f1();
> > In the above program, the first object ‘b’ of class type ‘A’ is working fine. But the object ‘a1’ of class type ‘B’ is giving an error which says – ‘incompatible types: test.A cannot be converted to test.B’
Is there a way to make the object ‘a1’ work?
Many Thanks
Satya

Читайте также:  Модуль zipfile python 3

in java we can have (declaration of superclass object)=(instanciation of subclass ) allowed but opposite to this not allowed

your doing wrong declaration of B object..
A’s reference object can access member of B .but cant be vice versa of it..
if u want to use class B member Then create object of this.

You wrote the constructor calling wrong.
The class name must match with the constructor name.
Here is this how you wrote
A b = new B();
Here the constructor is B(); and it does not match with class A .
B a1= new A
Here the constructor is A(); and doesn’t match with the class B.
So finally the rule is you should write the class and constructor name same.. Hope you understand..
Thank you…

Источник

Using the Keyword super

If your method overrides one of its superclass’s methods, you can invoke the overridden method through the use of the keyword super . You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass :

Here is a subclass, called Subclass , that overrides printMethod() :

public class Subclass extends Superclass < // overrides printMethod in Superclass public void printMethod() < super.printMethod(); System.out.println("Printed in Subclass"); >public static void main(String[] args) < Subclass s = new Subclass(); s.printMethod(); >>

Within Subclass , the simple name printMethod() refers to the one declared in Subclass , which overrides the one in Superclass . So, to refer to printMethod() inherited from Superclass , Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

Printed in Superclass. Printed in Subclass

Subclass Constructors

The following example illustrates how to use the super keyword to invoke a superclass’s constructor. Recall from the Bicycle example that MountainBike is a subclass of Bicycle . Here is the MountainBike (subclass) constructor that calls the superclass constructor and then adds initialization code of its own:

public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear)

Invocation of a superclass constructor must be the first line in the subclass constructor.

The syntax for calling a superclass constructor is

With super() , the superclass no-argument constructor is called. With super(parameter list) , the superclass constructor with a matching parameter list is called.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object . In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.

Источник

super and this keywords in Java

In java, super keyword is used to access methods of the parent class while this is used to access methods of the current class.

Читайте также:  Java nio buffer reset

this keyword is a reserved keyword in java i.e, we can’t use it as an identifier. It is used to refer current class’s instance as well as static members. It can be used in various contexts as given below:

  • to refer instance variable of current class
  • to invoke or initiate current class constructor
  • can be passed as an argument in the method call
  • can be passed as argument in the constructor call
  • can be used to return the current class instance

Java

super keyword

  1. super is a reserved keyword in java i.e, we can’t use it as an identifier.
  2. super is used to refer super-class’s instance as well as static members.
  3. super is also used to invoke super-class’s method or constructor.
  4. super keyword in java programming language refers to the superclass of the class where the super keyword is currently being used.
  5. The most common use of super keyword is that it eliminates the confusion between the superclasses and subclasses that have methods with same name.

super can be used in various contexts as given below:

  • it can be used to refer immediate parent class instance variable
  • it can be used to refer immediate parent class method
  • it can be used to refer immediate parent class constructor.

Java

Similarities in this and super

  • We can use this as well as superanywhere except static area. Example of this is already shown above where we use this as well as super inside public static void main(String[]args) hence we get Compile Time Error since cannot use them inside static area.
  • We can use this as well as superany number of times in a program.
  • Both are non-static keyword.

Java

See above we have used this 3 times. So this can be used any number of times.

Java

See above we have used super 2 times. So super can be used any number of times.

Note: We can use ‘this’ as well as ‘super’ any number of times but main thing is that we cannot use them inside static context.

Let us consider a tricky example of this keyword:

Java

//it is of S.O.P(first) of garcia method 22 //it is of S.O.P(second) of garcia method 33 //it is of S.O.P(a) of garcia method 22 //it is of S.O.P(b) of garcia method 33 //it is of S.O.P(first) of louis method 1 //it is of S.O.P(second) of louis method 2 //it is of S.O.P(m) of louis method 1 //it is of S.O.P(n) of louis method 2

Flow of program : First, it start from main and then we have new RR().garcia(100, 200) then flow goes to garcia method of RR class and then in that we have:

a = this.first b = this.second 

Here, what is happening is that the value of instance variable(i.e, first) and the value of static variable(i.e, second) are assigned to the garcia method’s local variables a and b respectively. Hence value of a and b comes out to be 22 and 33 respectively. Next we have new RR().louis(1, 2) hence here flow goes to the louis method of RR class and in that we have:

this.first = m this.second = n

Here, above what happens is that the value of the louis method’s local variables i.e, m and n are assigned to the instance as well as static variables i.e, first and second respectively.
Hence, the value of first and second variables are same which we have passed into the louis method i.e, 1 and 2 respectively.

Can we use both this() and super() in the same constructor?

An interesting thing to note here is that according to Java guidelines, this() or super() must be the first statement in the constructor block for it to be executed. So we cannot have them together in the same constructor as both need to be the first statement in the block for proper execution, which is not possible. Trying to do so would raise a compiler error.

Источник

Оцените статью