
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 within an instance method or a constructor. Using this, you can refer to the members of a class, such as constructors, variables, and methods.
Calling a Method using "this" 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 that accepts these two values.
From the constructor, we are invoking the setName() and setAge() methods using the "this" keyword by passing the obtained name and age values to them, respectively.
From the main method, we are reading the name and age values from the 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[]) { String name = "Rohan"; int age = 23; //Calling the constructor that accepts both values new Student(name, age).display(); } }
Following is the output of the above program:
Rohan Enter the age of the student: 18 Name of the Student: Rohan Age of the Student: 18