How to write our own marker interface in Java?

前端 未结 6 852
遇见更好的自我
遇见更好的自我 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:06

    Yes We can create our own Marker interface..See following one...

    interface Marker{   
    }
    
    class MyException extends Exception {   
        public MyException(String s){
            super(s);
        }
    }
    
    class A  {
        void m1() throws MyException{        
             if((this instanceof Marker)){
                 System.out.println("successfull");
             }
             else {
                 throw new MyException("Must implement interface Marker ");
             }      
        }   
    }
    
    public class CustomMarkerInterfaceExample  extends A implements Marker
    { // if this class will not implement Marker, throw exception
        public static void main(String[] args)  {
            CustomMarkerInterfaceExample a= new CustomMarkerInterfaceExample();
            try {
                a.m1();
            } catch (MyException e) {
    
                System.out.println(e);
            }
    
    
        }
    
    }
    

提交回复
热议问题