.net与java中关于访问性的差异

在.net下如下的代码是允许的
    class Program
    {
        static void Main(string[] args)
        {
            B b = new B();
            b.X = 20;
            b.Print(b);
            Console.ReadLine();
        }
    }

    class A {
        int x;
       public void Print(B b) {
            Console.Write(b.x); //可以通过编译
        }

        public int X {
            set {
                x = value;
            }
        }
    }

    class B : A { 
         public void Print(B b){
            Console.Write(b.x); //不可以通过编译
         }
    }
在这里的A类中可以访问B类中继承于A类的私有成员。
下面的是Java代码
public class A {
 private int x=0;
 public void Print(B b){
  System.out.println(b.x); // The field A.x is not visible 
   }
    public void setX(int value){
     x = value;
    }
 
 public void main(String[] args){
  B b = new B();
  b.setX(20);
  b.Print(b);
 }
}

class B extends A {
 
}
在Java中这样的访问是不允许的。

原文地址:https://www.cnblogs.com/77543/p/536097.html