英文:
Why is my instance variable accessible without an instance?
问题
My understanding of the Instance variables is that they are created when an object is created. If that is true then why can print the variable "data"? Shouldn't I have to create an object of class JavaTesting
first?
public class JavaTesting
{
static int a = 1;
private int data = 99;
@Test
public void f1()
{
System.out.println("Print a = "+a);
System.out.println("Print data = "+data);
}
}
英文:
My understanding of the Instance variables is that they are created when an object is created. If that is true then why can print the variable "data"? Shouldn't I have to create an object of class JavaTesting
first?
public class JavaTesting
{
static int a = 1;
private int data = 99;
@Test
public void f1()
{
System.out.println("Print a = "+a);
System.out.println("Print data = "+data);
}
}
答案1
得分: 2
你的方法 f1()
不是一个静态方法。这意味着它只能在一个实例上调用。无论哪个方法正在调用 f1()
,很可能首先创建了一个 JavaTesting
的实例。如果你将 f1()
改为静态方法,你的IDE可能会出问题,并开始显示红色警告标志。
英文:
Your method f1()
is not a static method. This means it can only be called on an instance. Whatever method is calling f1()
is probably creating an instance of JavaTesting
first. If you made f1()
static, your IDE would probably have a fit and start coughing up red flags.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论