(1)私有变量和私有方法
对于私有成员变量或方法,只有在本类中创建该类的对象时,这个对象才能访问自己的私有成员变量和类中的私有方法。
class Example4_14
{
private int money;
Example4_14()
{
money = 2000;
}
private int getMoney()
{
return money;
}
public static void main(String args[])
{
Example4_14 exa = new Example4_14();
exa.money =3000;
int m = exa.getMoney();
System.out.println("money = "+m);
}
}
F:/javacode>java Example4_14
money = 3000
(2)共有变量和共有方法
class Tom
{
public float weight;
public float f(float a,float b)
{
…… ……
}
}
在任何一个类中用类Tom创建一个对象后,该对象能访问自己的public变量和类中的public 方法
class Jerry
{
void g()
{
Tom cat = new Tom();
cat.weight = 23f; //合法
cat.f(3,4); //合法
}
}
(3) 友好变量和友好方法
class Tom
{
float weight; //weight是友好的float变量
float f(float a,float b) //方法f是友好方法
{
…… ……
}
}
Jerry和Tom是同一包中的类,那么
class Jerry
{
void g()
{
Tom cat = new Tom();
cat.weight = 23f; //合法
cat.f(3,4); //合法
}
}
(4)受保护的成员变量和方法
class Tom
{
protected float weight;
protected float f(double a,double b);
{
......
}
}
Jerry和Tom是同一包中的类,
class Jerry
{
void g()
{
Tom cat = new Tom();
cat.weight = 23f; //合法
cat.f(3,4); //合法
}
}
(5)public类和友好类
public 类
public class A
{ ......
}
友好类
class A
{ ......
} //在另外一个类中,使用友好类中创建对象时,要保证他们在同一个包中