Java की Sealed Classes
In this page:
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
// 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);
}
}
Login to try C/C++/Java/PHP code in the editor
Subclass Constraints
किसी sealed class की हर direct subclass को खुद तीनों में से बिल्कुल एक के रूप में declare होना चाहिए: final (उस branch को पूरी तरह बंद करते हुए), sealed (आगे extension सीमित रखते हुए), या non-sealed (उस branch को unrestricted extension के लिए फिर से खोलते हुए)। declarations की यह chain compiler द्वारा enforce की जाती है, इसलिए hierarchy का shape कभी चुपचाप नहीं बदल सकता।
उदाहरण: Subclass Constraints
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());
}
}
Login to try C/C++/Java/PHP code in the editor
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
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)));
}
}
Login to try C/C++/Java/PHP code in the editor
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
// 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());
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
// 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);
}
}
Login to try C/C++/Java/PHP code in the editor
final,sealedयाnon-sealedके बिना एक permitted subclass declare करना, जो एक compile error है।- किसी sealed class को ऐसी class से extend करना जो
permitsमें listed नहीं है, जिसे compiler reject कर देता है। - किसी sealed type पर pattern-matching
switchमें एकdefaultbranch जोड़ना, जो compiler को यह बताने से रोकता है कि कोई नई subclass handle नहीं हुई।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: