← Back to Advanced Java Course | Chapter 4: Modern Java Features | Lesson 4 of 12

Java की Sealed Classes

एक sealed class आपको ठीक-ठीक list करने देती है कि कौन सी classes इसे extend कर सकती हैं, जैसे एक बंद member list वाला club। कोई और join नहीं कर सकता।
Syntax
java
sealed interface Name permits SubA, SubB { }

final class SubA implements Name { }
final class SubB implements Name { }

Introduction to Sealed Classes

Sealed classes आपको explicitly यह सीमित करने देती हैं कि कौन सी दूसरी classes इन्हें extend या implement कर सकती हैं, बजाय इसके कि आपकी hierarchy codebase में कहीं भी किसी असंबंधित class द्वारा extend होने के लिए खुली रहे। यह आपको आपकी inheritance hierarchy कैसे बढ़ सकती है इस पर सटीक, सोच-समझकर control देता है।

उदाहरण: Introduction to Sealed Classes

java
// Define the class Main
public class Main {
	sealed interface Shape permits Circle, Square {}
	// Define the record Circle (an immutable data carrier)
	record Circle(double radius) implements Shape {}
	// Define the record Square (an immutable data carrier)
	record Square(double side) implements Shape {}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new Circle object and store it in s
		Shape s = new Circle(3);
		// Print a line to the console
		System.out.println(s);
	}
}

Subclass Constraints

किसी sealed class की हर direct subclass को खुद तीनों में से बिल्कुल एक के रूप में declare होना चाहिए: final (उस branch को पूरी तरह बंद करते हुए), sealed (आगे extension सीमित रखते हुए), या non-sealed (उस branch को unrestricted extension के लिए फिर से खोलते हुए)। declarations की यह chain compiler द्वारा enforce की जाती है, इसलिए hierarchy का shape कभी चुपचाप नहीं बदल सकता।

उदाहरण: Subclass Constraints

java
public class Main {
	sealed static class Vehicle permits Car, Truck {}
	static final class Car extends Vehicle {} // final -- closes this branch
	static non-sealed class Truck extends Vehicle {} // non-sealed -- reopens it
	public static void main(String[] args) {
		Vehicle v = new Car();
		System.out.println(v.getClass().getSimpleName());
	}
}

Sealed Classes and Pattern Matching

Sealed classes switch statements में pattern matching के साथ खासतौर पर अच्छी तरह जोड़ी बनाती हैं, क्योंकि compiler को permitted subclasses की पूरी, बंद list पहले से पता होती है। इसका मतलब है कि यह compile time पर verify कर सकता है कि आपका switch हर संभव case को cover करता है, बिना आपको एक defensive default branch जोड़ने की ज़रूरत के।

उदाहरण: Sealed Classes and Pattern Matching

java
public class Main {
	sealed interface Shape permits Circle, Square {}
	record Circle(double radius) implements Shape {}
	record Square(double side) implements Shape {}
	static double area(Shape s) {
		return switch (s) { // compiler verifies every case is covered, no default needed
			case Circle c -> Math.PI * c.radius() * c.radius();
			case Square sq -> sq.side() * sq.side();
		};
	}
	public static void main(String[] args) {
		System.out.println(area(new Square(4)));
	}
}

Reflection and Sealed Classes

आप किसी sealed class को runtime पर inspect करने के लिए reflection का उपयोग कर सकते हैं, जैसे यह जांचना कि कोई दिया गया Class sealed है या नहीं, या getPermittedSubclasses() के ज़रिए इसकी permitted subclasses की dynamically list बनाना। यह ज़्यादातर उन frameworks और tooling के लिए उपयोगी है जिन्हें किसी sealed hierarchy को generically introspect करना हो।

उदाहरण: Reflection and Sealed Classes

java
// Define the class Main
public class Main {
	sealed interface Shape permits Circle, Square {}
	// Define the record Circle (an immutable data carrier)
	record Circle(double radius) implements Shape {}
	// Define the record Square (an immutable data carrier)
	record Square(double side) implements Shape {}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println(Shape.class.isSealed());
		for (Class<?> c : Shape.class.getPermittedSubclasses()) {
			// Print a line to the console
			System.out.println(c.getSimpleName());
		}
	}
}

Real-World Domain Modeling

Sealed classes उन domain hierarchies को model करने के लिए एक स्वाभाविक fit हैं जहां आप वास्तव में states या variants के एक निश्चित, बंद set को represent करना चाहते हैं, जैसे किसी payment के संभावित outcomes (Success, Declined, Pending) बजाय एक open-ended list के जिसे कोई भी बाद में extend कर सके।

उदाहरण: Real-World Domain Modeling

java
// Define the class Main
public class Main {
	sealed interface PaymentResult permits Success, Declined, Pending {}
	// Define the record Success (an immutable data carrier)
	record Success(String transactionId) implements PaymentResult {}
	// Define the record Declined (an immutable data carrier)
	record Declined(String reason) implements PaymentResult {}
	record Pending(String reference) implements PaymentResult {}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new Declined object and store it in result
		PaymentResult result = new Declined("Insufficient funds");
		// Print a line to the console
		System.out.println(result);
	}
}
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. final, sealed या non-sealed के बिना एक permitted subclass declare करना, जो एक compile error है।
  2. किसी sealed class को ऐसी class से extend करना जो permits में listed नहीं है, जिसे compiler reject कर देता है।
  3. किसी sealed type पर pattern-matching switch में एक default branch जोड़ना, जो compiler को यह बताने से रोकता है कि कोई नई subclass handle नहीं हुई।

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.