Sunday 7 November 2021

Java: How to access this from Anonymous class?

Using ‘ClassName.this’, you can access the properties/methods associated with an object from anonymous class.

 

AccessThisFromAnonymousClass.java

package com.sample.app.classes;

public class AccessThisFromAnonymousClass {

	private final double PI = 3.14;

	private interface Circle {
		public double area(double radius);
	}

	public static void main(String args[]) {
		Circle c1 = new Circle() {

			@Override
			public double area(double radius) {
				return AccessThisFromAnonymousClass.this.PI * radius * radius;
			}

		};

		double area = c1.area(5);

		System.out.println(area);
	}

}

Output

78.5


You may like

Interview Questions

Java: Get the index of first occurrence of a substring

Java: Get the index of last occurrence of a substring

Java: Get all the indexes of occurrence of a substring

Java: How to replace a value in ArrayList or LinkedList

Why do we declare logger with static and final?

No comments:

Post a Comment