← Back to Core Java Course | Chapter 9: OOP Advanced | Lesson 8 of 8

Java की Anonymous Classes

एक anonymous class बिना नाम की एक one-time class है, तुरंत बनाई गई, एक job के लिए hired एक temporary helper जैसी। इसे उपयोग किया जाता है जब आपको किसी चीज़ का एक quick custom version चाहिए।
Syntax
java
InterfaceOrClass variable = new InterfaceOrClass() {
    @Override
    public returnType methodName() {
        // body
    }
};

What is an Anonymous Class?

एक anonymous class आपको एक single expression में एक one-off subclass या interface implementation declare और instantiate करने देती है, इसे कोई नाम दिए बिना।

यह सबसे उपयोगी है जब आपको बिल्कुल एक बार उपयोग होने वाला एक छोटा, throwaway implementation चाहिए, जैसे एक quick event listener या comparator।

उदाहरण: What is an Anonymous Class?

java
interface Greeting {
	void greet();
}
public class Main {
	public static void main(String[] args) {
		Greeting g = new Greeting() { // one-off implementation, no name
			public void greet() {
				System.out.println("Hi!");
			}
		};
		g.greet();
	}
}

Anonymous Classes with Abstract Classes

आप instantiation के point पर इसके abstract methods की body inline supply करके एक abstract class को anonymously extend कर सकते हैं। यह उस logic के लिए एक अलग named subclass file लिखना skip करता है जिसे आप सिर्फ एक जगह उपयोग करेंगे।

उदाहरण: Anonymous Classes with Abstract Classes

java
abstract class Shape {
	abstract void draw();
}
public class Main {
	public static void main(String[] args) {
		Shape s = new Shape() { // extends abstract class anonymously
			void draw() {
				System.out.println("Drawing shape");
			}
		};
		s.draw();
	}
}

Anonymous Classes as Method Arguments

Anonymous classes आमतौर पर सीधे methods को arguments के रूप में pass की जाती हैं जो एक interface या abstract type expect करते हैं, जैसे Runnable या Comparator। यह implementation को call site के बिल्कुल बगल में रखता है बजाय codebase में बिखरे होने के।

उदाहरण: Anonymous Classes as Method Arguments

java
import java.util.Arrays;
import java.util.Comparator;
public class Main {
	public static void main(String[] args) {
		Integer[] nums = {5, 2, 8};
		Arrays.sort(nums, new Comparator<Integer>() { // passed directly as an argument
			public int compare(Integer a, Integer b) {
				return b - a;
			}
		});
		System.out.println(Arrays.toString(nums));
	}
}

Accessing Local Variables

एक anonymous class अपने enclosing scope से local variables पढ़ सकती है, लेकिन सिर्फ अगर वे variables effectively final हों (initialization के बाद कभी reassigned न हों)।

Compiler creation time पर एक copy capture करता है, इसलिए class original variable में बाद के changes observe नहीं कर सकती।

उदाहरण: Accessing Local Variables

java
interface Printer {
	void print();
}
public class Main {
	public static void main(String[] args) {
		final String message = "Hello"; // effectively final
		Printer p = new Printer() {
			public void print() {
				System.out.println(message);
			}
		};
		p.print();
	}
}

Limitations of Anonymous Classes

Anonymous classes का अपना named constructor नहीं हो सकता, एक साथ कई interfaces implement नहीं कर सकतीं, और body कुछ lines से बड़ी होने पर पढ़ना मुश्किल हो जाता है।

ज़्यादा complex किसी भी चीज़ के लिए, एक lambda (functional interfaces के लिए) या एक proper named class कहीं ज़्यादा clearly पढ़ती है।

उदाहरण: Limitations of Anonymous Classes

java
interface Task {
	void run();
}
public class Main {
	public static void main(String[] args) {
		Task t = new Task() { // no named constructor, only one interface at a time
			public void run() {
				System.out.println("Running task");
			}
		};
		t.run();
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक anonymous class में एक constructor जोड़ने की कोशिश करना, जो possible नहीं।
  2. एक anonymous class में उपयोग किए local variable बदलना, जिसे final या effectively final होना चाहिए।
  3. Closing brace के बाद semicolon भूल जाना।
चैप्टर सारांश
  • Polymorphism और abstraction एक interface को कई implementations के लिए stand करने देते हैं, abstract classes और interfaces उपयोग करते हुए।
  • एक class कई interfaces implement कर सकती है, जबकि encapsulation internal data protect करता है।
  • Inner और anonymous classes आपको दूसरे code के अंदर classes define करने देती हैं।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.