ClassName.this
is used to refer the outer class object from inner class.
Test.java
Let
me explain with an example.
As you see above image, I defined Employee
class, where Formatter is the inner class inside it. Formatter class defines
formattedInfo method, it accesses the super class object data using ‘Employee.this’.
Find the below working application.
Employee.java
package com.sample.app.model; public class Employee { private int id; private String firstName; private String lastName; public Employee(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; } public Formatter formatter() { return new Formatter(); } public class Formatter { public String formattedInfo() { String firstName = Employee.this.firstName; String lastName = Employee.this.lastName; return firstName.toUpperCase() + "," + lastName.toUpperCase(); } } }
Test.java
package com.sample.app; import com.sample.app.model.Employee; import com.sample.app.model.Employee.Formatter; public class Test { public static void main(String args[]) { Employee emp = new Employee(1, "Gopi", "Battu"); Formatter formatter = emp.formatter(); String formattedInfo = formatter.formattedInfo(); System.out.println("Formatted Information : " + formattedInfo); } }
When
you ran Test.java, you can able to see below message in console.
Formatted
Information : GOPI,BATTU
You may like
Programming
Questions
Miscellaneous
No comments:
Post a Comment