What happens if the parent and the child class have a field with same identifier?

Abstract

The super keyword is used to represent an instance of the parent class which is created implicitly for each object of the child class. The super keyword can be used to invoke the parent class methods and constructors. It can also be used to access the fields of the parent class.

The this keyword is used to represent the current instance of a class. It is used to access the instance variables and invoke current class methods and constructors. The this keyword can be passed as an argument to a method call representing the current class instance.

Scope of the Article

  • The article will explain this and super keyword used in Java Programming.
  • Examples using this and super keyword.
  • Differences and similarities between this and super keyword in Java.

Introduction

Java provides many implicit keywords among those this and super are two reference variables. The this and super keywords resemble the reference variable pointing to an instance of a class or a parent class (superclass), respectively.

this: this is the reserved keyword in Java that can be used to invoke the constructors, methods, static members, etc. of the current instance of a class.

super: super is the reserved keyword in Java that is used to invoke constructors and methods of the parent class. This is possible only when one class inherits another class (child class extends parent class).

What is this keyword in Java?

class Code{ int value; void assign(int var){ this.value = var; } }

Let us understand the use of this keyword using the above code snippet. As we can see that we have an instance variable value and a parameter var of the assign method. If we want to assign var to the instance variable value inside the class then we have to use the this keyword. In technical terms we are using this keyword to refer to the current object of the Code class.

this is a special keyword in Java that is used to refer to an instance of the current class. Using the this keyword, we can refer to the current class's methods, constructors, instance variables, and many more. We cannot use the this keyword as an identifier in Java.

Uses of “this” keyword in Java

  • It can be used to refer to the current class instance variables.
  • It can be passed as an argument in the method call representing the current object of the class.
  • It can be used to return the current class instance from any of its instance methods.
  • It can be used to access instance and static variables of the current instance.
  • It can be passed as an argument in the constructor call.
  • It is used to initiate a constructor of the current class.
  • It can be used to invoke the current class methods.

Example of this keyword in Java

Example 1

The this keyword can be used to access and modify the instance and static variables. Thus, we can change the values of the variables that are declared inside the class through the this keyword. Also, this keyword can be used to differentiate between method-specific and class variables. Let us see an example.

Code:

// Illustration class class Illustration { // declaring an instance variable int instanceVar = 5; // declaring an static variable static int staticVar = 10; void Scaler() { // Method-specific variables int instanceVar = 20; int staticVar = 40; // referring to the current class instance and static variables this.instanceVar = 50; this.staticVar = 100; // printing the current class instance and static variable. System.out.println("Value of instance variable : " + this.instanceVar); System.out.println("Value of static variable : " + this.staticVar); // printing the method specific variables. System.out.println("instanceVar inside method : " + instanceVar); System.out.println("staticVar inside method: " + staticVar); } } public class Main { public static void main(String[] args) { // creating an instance of Illustration class Illustration obj = new Illustration(); obj.Scaler(); } }

Output:

Value of instance variable : 50 Value of static variable : 100 instanceVar inside method : 20 staticVar inside method: 40

Explanation:

  • In the Illustration class, instanceVar and staticVar are instance and static variables respectively. Both the variables are referred in the Scaler method by using the "this" keyword.
  • instanceVar is initialized with value 5, and staticVar is initialized with value 10. The Scaler method assigns 50 and 100 to the instanceVar and staticVar variables respectively.
  • There are other two method-specific variables having the same names. We are able to differentiate between variables inside the class and methods by using this keyword.

Example 2

The “this” keyword is used to invoke the methods of the current object or class. Let us see an example.

Code:

// Illustration class class Illustration { // current class method void scaler() { System.out.print("My name is "); } void name() { // invoking current class scaler method. this.scaler(); System.out.println("Soham."); } } public class Main { public static void main(String[] args) { // creating an instance of Illustration class Illustration obj = new Illustration(); obj.name(); } }

Output:

Explanation:

In the above example, the Illustration class has two methods scaler and name. The scaler method is invoked inside the name method by using the this keyword.

Example 3

The this keyword is used to invoke the constructors of the current class. Suppose a class has two constructors: no-arg and parametrized constructors.

Code:

// Illustration class class Illustration { // simple constructor Illustration() { // invoking parameterized constructor this(10); } // parameterized constructor Illustration(int x) { System.out.println("Current class parameterized constructor invoked."); System.out.println("Number is : " + x); } } public class Main { public static void main(String[] args) { // creating an instance of Illustration class Illustration obj = new Illustration(); } }

Output:

Current class parameterized constructor invoked. Number is : 10

Explanation:

In the above example, there are two constructors. The no argument constructor is called while creating the object, and the parameterized constructor is called within the no argument constructor by using the “this” keyword.

Example 4

The this keyword can be passed as an argument in a method representing an object of a class. At industry level it is used in event handlers or at places where we have to provide reference of one class to another class. Let us understand it practically.

Code:

// Illustration class class Illustration { int value = 5; // print method void print(Illustration ob) { System.out.println("ob.value = " + ob.value); } void invoke() { // print method is invoked by passing this as an argument print(this); } } public class Main { public static void main(String[] args) { // creating an instance of Illustration class Illustration obj = new Illustration(); obj.invoke(); } }

Output:

Explanation:

In the above example, we are passing the this keyword as an argument to call the print method within the invoke method.

Example 5

The “this” keyword can be passed as an argument in the constructor call. By passing this as an argument in the constructor call we can exchange data from one instance to another. This makes exchange of data between multiple classes or objects a lot easier.

// A class class A { // instance variable B tmp; // parameterized constructor A(B tmp) { this.tmp = tmp; } // print method void print() { System.out.println("The number is : " + tmp.val); } } // B class class B { // instance variable int val = 50; // constructor B() { // creating instance of A // passing “this” as an argument in constructor call A obj = new A(this); obj.print(); } } public class Main { public static void main(String[] args) { B b = new B(); } }

Output:

Explanation:

In the above example, we have passed the this keyword as an argument in the constructor call. Here A and B are two classes; parameterized constructor of A is called in class B by creating an object of class A and passing this as an argument.

Example 6

The this keyword is used to return the current instance of a class. Methods of the class can be called directly at the time of creating an object using this

// illustration class class Illustration { Illustration getIllustration() { // returing the instance of current class return this; } void print() { System.out.println("Hello World!"); } } public class Main { public static void main(String[] args) { new Illustration().getIllustration().print(); } }

Output:

Explanation:

In the above example, the getIllustration method returns the current class instance and through which we called the print method.

What is a super keyword in Java?

Concept of Immediate Parent:

class A{ void methodP(){ // method } } class B extends A{ void methodC(){ // method } } class C extends B{ void methodGC(){ // method } }

Let us understand the concept of immediate parent. In the above code snippet of multi-level inheritance class B extends class A, it implies class A is immediate parent of class B. Similarly class C extends class B and now class C has two parents i.e., class A and class B, where class B is immediate parent of class C.

super is a special keyword in Java that is used to refer to the instance of the immediate parent class. Using the super keyword, we can refer to the immediate parent class's methods, constructor, instance and static variables, etc. We cannot use the super keyword as an identifier in Java as it is a reserved keyword.

Uses of super Keyword in Java

  • It is used to refer to an instance variable of the immediate parent class.
  • It is used to invoke a method of the immediate parent class.
  • It is used to invoke a constructor of immediate parent class.

Examples of super Keyword in Java

Example 1

The “super” keyword is used to refer to an instance variable of an immediate parent class.

// parent class class Parent { int a = 50; String s = "Hello World!"; } // child class extending parent class class Child extends Parent { int a = 100; String s = "Happy Coding!"; void print() { // referencing to the instance variable of parent class System.out.println("Number from parent class is : " + super.a); System.out.println("String from parent class is : " + super.s); // printing a and s of the current/child class System.out.println("Number from child class is : " + a); System.out.println("String from child class is : " + s); } } public class Main { public static void main(String[] args) { // creating instance of child class Child obj = new Child(); obj.print(); } }

Output:

Number from parent class is : 50 String from parent class is : Hello World! Number from child class is : 100 String from child class is : Happy Coding!

Explanation:

  • In the above example, the Child class extends the Parent class. Both have two instance variables, a and s.
  • In the Child class, the print method calls the instance variables of the parent class using the super keyword.
  • In comparison, the instance variables of child class don't need one. It doesn't matter whether the instance variable of parent class and child class share the same name; they can hold different values and are not overridden.

Example 2

The super keyword is used to invoke an immediate parent class method.

// parent class class Parent { // declaring display method parent class void display() { System.out.println("Hi I am parent method."); } } // child class extending parent class class Child extends Parent { // declaring display method in Child class void display() { System.out.println("Hi I am child method."); } void print() { // invoking display method from parent class super.display(); // display method from child class display(); } } public class Main { public static void main(String[] args) { // creating instance of child class Child obj = new Child(); obj.print(); } }

Output:

Hi I am parent method. Hi I am child method.

Explanation:

  • In the above example, the Child class extends Parent class. Both have a display method.
  • The print method in the child class invokes the display method of the parent class by using the super keyword.
  • The example says that to invoke the methods in the child class from the parent class, we must use the “super” keyword.

Example 3

The super keyword is used to invoke an immediate parent class constructor.

// parent class class Parent { // parent class constructor Parent() { System.out.println("Hi I am Parent class constructor."); } } // child class extending parent class class Child extends Parent { // child class constructor Child() { // invoking parent class constructor super(); } } public class Main { public static void main(String[] args) { // creating instance of child class Child obj = new Child(); } }

Output:

Hi I am Parent class constructor.

Explanation:

In the above example, the child class extends parent class. While creating an object of the child class, the constructor of the child class is called, where the parent class constructor is invoked using the “super” keyword.

Note:

When we create an object of a child class, a corresponding object of the superclass is implicitly created which is referred to by the super keyword.

Even if we don't invoke the parent class constructor using super(); in the example above, the same output is generated because the child constructor implicitly calls the parent class default constructor.

Difference Between this and super Keyword in Java

this keyword in Javasuper keyword in Java
this is an implicit reference variable keyword used to represent the current class. super is an implicit reference variable keyword used to represent the immediate parent class.
this is to invoke methods of the current class. super is used to invoke methods of the immediate parent class.
this is used to invoke a constructor of the current class. super is used to invoke a constructor of the immediate parent class.
this refers to the instance and static variables of the current class. super refers to the instance and static variables of the immediate parent class.
this can be used to return and pass as an argument in the context of a current class object. super can be used to return and pass as an argument in the context of an immediate parent class object.

Similarities Between this and super Keyword in Java

  1. Both this and super are non-static, so they can't be used in static context. It means that we cannot use both the keywords in the main method in Java.

Example 1

public class Main { int a = 50; public static void main(String[] args) { System.out.println(this.a); } }

Output:

Main.java:4: error: non-static variable this cannot be referenced from a static context System.out.println(this.a);

Explanation:

In the above example, we are referencing the non-static variable "this" in the static context. This led to a compiler error.

  1. Both super and this keywords in Java can be used in constructor chaining to call another constructor. this() calls the no-argument constructor of the current class, and super() calls the no-argument constructor of the parent class.

Example 2

// declaring parent class class Parent { Parent() { System.out.println("Parent class no argument constructor"); } Parent(String s) { System.out.println("Parent class parameterized " + s); } } // Child class extends parent class class Child extends Parent { Child() { // referring current class parameterized constructor this("constructor."); System.out.println("Child class no-argument constructor."); } Child(String s) { // referring parent class parameterized constructor super("constructor."); System.out.println("Child class parameterized " + s); } } public class Main { public static void main(String[] args) { // instance of child class Child obj = new Child(); } }

Output:

Parent class parameterized constructor. Child class parameterized constructor. Child class no-argument constructor.

Explanation:

In the above example, we first forward a call from the child class no-argument constructor to the child class parameterized constructor using the this keyword. We are forwarding a call to the parent class parameterized constructor using the super keyword from a child class parameterized constructor.

  1. this and super must be the first statement if used inside the constructor. This means we cannot call both statements in a single constructor.

Example 3

// declaring parent class class Parent{ Parent(){ System.out.println("Parent class no argument constructor"); this("constructor."); } Parent(String s){ System.out.println("Parent class parameterized "+s); } } public class Main { public static void main(String[] args) { // instance of child class Parent obj = new Parent(); } }

Output:

Main.java:5: error: call to this must be first statement in constructor this("constructor."); ^ 1 error

Explanation:

In the above example, the error will be displayed as shown in output because the this() statement is not executed first.

Can we Use Both this() and super() in the Same Constructor?

No, we cannot use the this() and super() in the same constructor. If we want to use this() or super() inside a constructor, they must be written (executed) at first. Both this() and super() cannot be executed simultaneously, hence “this()” and “super()” in Java cannot be used in the same constructor.

Important Points About this() and super() in Java

  • this() as well super() can be used exactly once inside the constructor.
  • If we use this() followed by super() or super() followed by this() we will get compile-time error. It is due to either this() or super() can be the first statement inside the constructor, not both.
  • Inside the constructor, we cannot call the this() and super() recursively. Example

// declaring parent class class A { A() { this(" "); System.out.println("No argument constructor"); } A(String s) { this(); System.out.println("Parameterized constructor"); } } public class Main { public static void main(String[] args) { // instance of child class A obj = new A(); } }

Output

Main.java:3: error: recursive constructor invocation A(){ ^ 1 error

In the above example, we have recursively made calls for the constructor, which leads to a compile-time error.

Conclusion.

  • super” and “this” in Java are two predefined keywords, that cannot be used as an identifier.
  • super” in Java is used to refer to methods, static and instance variables, constructors of an immediate parent class.
  • this” in Java is used to refer to methods, static and instance variables, constructors of a current class.
  • If we include “this()” or “super()” inside the constructor, it must be the first statement inside it.
  • this()” and “super()” cannot be used inside the same constructor, as both cannot be executed at once (both cannot be the first statement).
  • this” can be passed as an argument in the method and constructor calls.

FAQ’s

1. Can we have “this()” and “super()” together?

No, we can not use “this()” and “super()” together.

2. Why “this()” and “super()” keywords cannot be used together?

this()” is used to call the constructor of the current class and “super()” is used to call the constructor of the immediate parent class. If a user wants to call a parent or a current class constructor using the “super()” or “this()” keyword, then it must be the first statement inside the constructor, but both “super()” and “this()” cannot be the first statement simultaneously due to this reason “this()” and “super()” keywords cannot be used together.

3. Why do we use super keyword in Java?

We use the super keyword to refer to the parent class instance, to invoke parent class methods, static and instance variables. The “super()” is used to invoke the immediate parent class constructor.

4. Why super keyword is used first?

Java enforces that the call to super (explicit or not) must be the first statement in the constructor. This is to prevent the subclass part of the object from being initialized before the superclass part of the object being created.

What happens if the parent and the child class have a field with same identifier in Java?

what happens if both superclass and subclass have a field with same name? Sub class field will hide the Super class field.

What happens if both superclass and subclass have a field with same name?

When declaring a variable in a subclass with the same name as in the superclass, you are hiding the variable, unlike methods which are overwritten.

Can we have same data members in parent and child classes?

Yes, it is possible to have same data member in Parent and Child classes. Now, we will see the capability or strength of the Parent and Child class. The Parent class reference can hold its own object and Child class object as well and The Child class reference hold its own object only.

Are constructors and initializers also inherited to sub classes?

Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

Toplist

Neuester Beitrag

Stichworte