public class ModifierTest1
{
public static void main( String[] args )
{
A a = new A();
//System.out.println(a.s);
a.f();
}
}class A
{
private int i;
private String s;
public A()
{
i = 123;
s = "hello";
}
public void f()
{
A a = new A();
System.out.println(a.i + a.s );
}
}
为啥f()中创建的对象能直接使用使用a.i和a.s,私有还能这么用?在main函数中这么做却不行?
{
public static void main( String[] args )
{
A a = new A();
//System.out.println(a.s);
a.f();
}
}class A
{
private int i;
private String s;
public A()
{
i = 123;
s = "hello";
}
public void f()
{
A a = new A();
System.out.println(a.i + a.s );
}
}
为啥f()中创建的对象能直接使用使用a.i和a.s,私有还能这么用?在main函数中这么做却不行?
private 意思是只有本类成员才能访问!f()方法和那几个私有变量都是在一个类中的,当然可以访问了!
还有就是main方法,你的main方法因为在其他方法中了,是无权访问类A中的私有变量的!
如果你在类A中也定义了main方法,还是访问不到私有变量,这是因为main方法是静态方法,不能访问非静态成员变量和非静态方法的!