- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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
- Related Articles
- Can we call a method on "this" keyword from a constructor in java?
- Can we return this keyword from a method in java?
- Can we use "this" keyword in a static method in java?
- Can we call methods of the superclass from a static method in java?
- Can we make Array volatile using volatile keyword in Java?
- When can we call wait() and wait(long) methods of a Thread in Java?
- Call methods of an object using reflection in Java
- This keyword in Java
- Can we override final methods in Java?
- Can we synchronize abstract methods in Java?
- Can we override default methods in Java?
- How can we sort a string without using predefined methods in Java?
- Can we override private methods in Java\n
- Can we call Superclass’s static method from subclass in Java?
- How can we call garbage collection (GC) explicitly in Java?

Advertisements