![](/img/trans.png)
[英]Can't acces a public method from a public class outside the class in Android Studio
[英]Why can't I acces the public variable from the Test class in the main function?
我是学习Java的新手,但我不明白为什么我不能println变量prvvar
。 为什么需要将其设置为静态?
package myproject;
class Test
{
private int prvvar=2;
public int pbvar=3;
}
主班:
public class bycicleDemo
{
public static void main(String[] args) {
Test da = new Test();
System.out.println(Test.pbvar);
}
}
在Java中,非静态变量是对象关联的,而静态变量是类关联的。
在您的情况下, pbvar
是非静态变量,因此您无法使用需要使用object访问它的类名来访问它。 如下
public class BycicleDemo
{
public static void main(String[] args) {
Test da = new Test();
System.out.println(da.pbvar);
}
}
如果将此pbvar
声明为static,则如下所示,则使用类名进行的调用是正确的。
package myproject;
class Test
{
public static int pbvar=3;
private int prvvar=2;
}
根据Java标准,类名应以大写字母BycicleDemo开头 。
由于pbvar
不是静态的,因此无法通过该类进行访问。 通过新创建的实例而不是System.out.println(da.pbvar);
访问它System.out.println(da.pbvar);
。
如果您像这样声明pbvar
,则public static int pbvar=3;
您的示例: System.out.println(Test.pbvar);
会工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.