Public vs. Protected abstract class method

This question already has an answer here:

  • In Java, difference between package private, public, protected, and private 26 answers

  • The public abstract method will be accessible in the other package where as the protected abstract method can not be accessed. Check the example below.

    An abstract class with both public and protected abstract methods

    package package1;
    
    public abstract class MyClass {
      abstract protected String method1();
      abstract public String method2();
    }
    

    Another package which extends the class and implements the abstract class.

    package package2;
    
    import package1.MyClass;
    
    public class MyClassImpl extends MyClass {
      @Override
      protected String method1() {
        return "protected method";
      }
    
      @Override
      public String method2() {
        return "public method";
      }
    }
    

    Main class for accessing the abstract method.

    package package2;
    
    import package1.MyClass;
    
    public class MainClass {
      static MyClass myClass = new MyClassImpl();
    
      public static void main(String[] args) {
        System.out.println(myClass.method1());   // This is compilation error.
        System.out.println(myClass.method2());
      }
    }
    
    链接地址: http://www.djcxy.com/p/24066.html

    上一篇: 在java方法中省略public修饰符

    下一篇: 公共与受保护的抽象类方法