Город МОСКОВСКИЙ
00:01:20

Java Sealed classes in ONE minute

Аватар
Кotlin Семинары
Просмотры:
26
Дата загрузки:
01.12.2023 23:56
Длительность:
00:01:20
Категория:
Технологии и интернет

Описание

SEALED CLASSES

Declaring a class or interface as sealed enables you to control the classes or interfaces that can extend or implement it.


With the sealed modifier, you can declare a class as a sealed class.
A sealed class can provide a permits clause that lists the classes that extend it directly.
If a class doesn’t appear in this list, it isn’t allowed to extend the sealed class.
public abstract sealed class Plant permits Herb, Shrub, Climber {
}

public final class Shrub extends Plant {}
public non-sealed class Herb extends Plant {}
public sealed class Climber extends Plant permits Cucumber{}

public final class Cucumber extends Climber {}

int process(Plant plant) {
return switch (plant) {
case Cucumber c ➡️ harvestCucumber(c);
case Climber cl ➡️ sowClimber(cl);
case Herb h ➡️ sellHerb(h);
case Shrub s➡️ pruneShrub(s);
};
}



“Don’t write code that is not required.”

Sealed classes help you to follow this practice in a few places.
They free you from writing code to handle subclasses that don’t exist.
Sealed classes also help you control and define hierarchies that align more precisely with business use cases.
Using this functionality, you can create, in a declarative manner, hierarchies that are accurate and secure.

https://blogs.oracle.com/javamagazine/post/java-sealed-classes-fight-ambiguity

Рекомендуемые видео