How private method of super class are resolved?

前端 未结 5 583
抹茶落季
抹茶落季 2021-01-02 22:50
class A{ 
  private void sayA(){
     System.out.println(\"Private method of A\");
  }
  public static void main(String args[]){
      A instanceA=new B();
      ins         


        
5条回答
  •  臣服心动
    2021-01-02 23:29

    It's because you're assigning B to A, so the resulting instance has access to the methods of A.

    If you change to B instanceA=new B(), the subsequent line will not compile (which I believe is what you expected?).

    class A{ 
      private void sayA(){
         System.out.println("Private method of A");
      }
      public static void main(String args[]){
          B instanceA=new B();
          instanceA.sayA(); # This line won't compile/run.
      }
    }
    
    class B extends A{
    }
    

提交回复
热议问题