为什么我的实例变量可以在没有实例的情况下访问?

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年5月30日 02:52:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/62092840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定