Can we call a method on "this" keyword from a constructor in java?


The “this ” keyword in Java is used as a reference to the current object, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.

Calling a method using this keyword from a constructor

Yes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.

Example

In the following Java program, the Student class contains two private variables name and age with setter methods and, a parameterized constructor which accepts these two values.

From the constructor, we are invoking the setName() and setAge() methods using "this" keyword by passing the obtained name and age values to them respectively.

From the main method, we are reading name and, age values from user and calling the constructor by passing them. Then we are displaying the values of the instance variables name and class using the display() method.

public class Student {
   private String name;
   private int age;
   public Student(String name, int age){
      this.setName(name);
      this.setAge(age);
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      //Reading values from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      //Calling the constructor that accepts both values
      new Student(name, age).display();
   }
}

Output

Rohan
Enter the age of the student:
18
Name of the Student: Rohan
Age of the Student: 18

Updated on: 29-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements