
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
Call 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