
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 Methods Using This Keyword in Java
The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it. But, you should call them only from instance methods (non-static).
Example
In the following example, the Student class has a private variable name, with setter and getter methods, using the setter method we have assigned value to the name variable from the main method and then, we have invoked the getter (getName) method using "this" keyword from the instance method.
public class ThisExample_Method { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void display() { System.out.println("name: "+this.getName()); } public static void main(String args[]) { ThisExample_Method obj = new ThisExample_Method(); Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); String name = sc.nextLine(); obj.setName(name); obj.display(); } }
Output
Enter the name of the student: Krishna name: Krishna
Advertisements