How to write our own marker interface in Java?

前端 未结 6 850
遇见更好的自我
遇见更好的自我 2021-02-04 06:15

I know marker interface in java. It is used to define a specific behaviour about a class. For example, Serializable interface has the specific ability to store an object into by

6条回答
  •  抹茶落季
    2021-02-04 07:05

    Marker interface has no method. Java has built-in marker interface like Serializable, Clonable & EventListner etc that are understand by JVM.

    We can create our own marker interface, but it has nothing to do with JVM, we can add some checks with instanceOf.

    1. Create the empty interface

      interface Marker{    }
      
    2. Write a class and implements the interface

      class A implements Marker {
          //do some task
      }
      
    3. Main class to check the marker interface instanceof

      class Main {
          public static void main(String[] args) {
              A ob = new A(){
              if (ob instanceof A) {
                  // do some task
              }
          }
      }
      

提交回复
热议问题