假设B与A在同一个包中,则
Java代码
class B
{
void g()
{
A a=new A();
A.weight=100;//合法
A.f(3,4); //合法
}
}
private: 只能在本类中访问。
Java代码
class Test
{
private int money;
Test()
{
money=2000;
}
private int getMoney()
{
return money;
}
public static void main(String args[])
{
Test te=new Test();
te.money=3000; //合法
int m=te.getMoney(); //合法
System.out.println("money="+m);
}
}
PS: 实际上,把重要的数据修饰为private,然后写一个public的函数访问它,正好体现了OOP的封装特性,是OOP安全性的体现。
二 访问权限修饰符修饰类
1,不能用protected和private修饰类。
2,用friendly修饰的类叫友好类,在另外一个类中使用友好类创建对象时,要保证它们在同一包中。
三 访问权限修饰符与继承
这里的访问修饰符指的是修饰成员变量和方法。可以分为两种情况:
1,子类与父类在同一包中
此时只有声明为private的变量与方法不能被继承(访问)。
Java代码
class Father
{
private int money ;
int weight=100;
}
class Son extends Father
{
viod f()
{
money=10000;// 非法
weight=100; // 合法
}
}