How private method of super class are resolved?

前端 未结 5 585
抹茶落季
抹茶落季 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:24

    InstanceA is the instance of A actually, so it can call the functions of A, but if the function is private, means that only the class declares the field can see it. eg:

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

提交回复
热议问题