How to write a Sealed Interface ?

How to write a Sealed Interface ?

Finally, we've come to the last part of the Sealed concept. We've already learnt - what, why and how parts in last three articles.

It's time to see the second part of 'how' which is writing Sealed Interfaces.

Just like classes, an interface can be sealed by using sealed modifier along with permits clause like below -

sealed interface Celestial permits Planet, Star, Comet { ... } 
        

One more example - package com.example.expression;


package com.example.expression

public sealed interface Expr permits ConstantExpr, PlusExpr { ... }

public final class ConstantExpr implements Expr { ... }
public final class PlusExpr     implements Expr { ... }        

That's it, we're done! Thanks for reading this far !

Ending by asking a question about what we learnt, see if you can answer it?

Can a class be non-sealed and final at the same time?


要查看或添加评论,请登录

Shiv Dhiman的更多文章

  • Team Fridays | Decision-making activity around Conflicting views

    Team Fridays | Decision-making activity around Conflicting views

    This Friday's session with the team was around a decision-making activity around conflicting views on a problem…

  • Team Fridays | Learning & Sharing

    Team Fridays | Learning & Sharing

    Learning and sharing are key to the team's cohesiveness and growth. And, Fridays, I believe, are the best days to do so.

  • How to write a Sealed Class ?

    How to write a Sealed Class ?

    In the last two articles, we discussed the what and why parts - as what's a sealed class and second, why do we even…

  • Why do we need a Sealed Class?

    Why do we need a Sealed Class?

    Hello Folks, In the last article here, we discussed about what is exactly the concept of Sealed? Today, we are going to…

  • What is a Sealed Class/Interface ?

    What is a Sealed Class/Interface ?

    Hello Folks, Java version 17 has been released around 15 days ago in Sept, 2021. There are a number of features that…

社区洞察

其他会员也浏览了