Why subclass in another package cannot access a protected method?

后端 未结 7 2214
一向
一向 2020-11-30 05:07

I have two classes in two different packages:

package package1;

public class Class1 {
    public void tryMePublic() {
    }

    protected void tryMeProtect         


        
7条回答
  •  一向
    一向 (楼主)
    2020-11-30 05:39

    It can be acheived by two ways

    1. Either by making an object of Child class and then accessing the protected method of Parent class.

    PACKAGE 1

    public class Class1 {
        protected void m1() {
            System.out.println("m1 called");
        }
    }
    

    PACKAGE2

    public class Class2 extends Class1 {
    
        public static void main(String[] args) {
            Class2 class2 = new Class2();
            class2.m1();
        }
    }
    

    2. Or by directly calling the method from the Child class

    eg tryMeProtected();

提交回复
热议问题