在JAVA中何时使用静态/非静态变量

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

When to use static/non-static variable in JAVA

问题

我理解非静态和静态变量之间的区别,但我只是不知道何时使用每种类型。所以在上面的代码中,为什么函数 Staf 不能是静态的?(以及它应该何时是静态的?)

英文:

I don't know when to use a static/non-static variable in a program.

package slides;

public class Person {
		
	String name;
	int age;
	boolean isStaff;
	
	public Person(String name, int age, boolean isStaff) {
		// TODO Auto-generated constructor stub
		
		this.name = name;
		this.age = age;
		this.isStaff = isStaff;
		System.out.println(this);
	}
	
	/*
	public static boolean Staf () {
		
		return isStaff;
	}
	*/

}

I understand the difference between the non-static/static variable but I just don't know when to use each. So in the above code, why the function Staf can not be static? (and when it should be static?)

答案1

得分: 2

根据上一个问题,你不理解这个区别。每个非静态方法都隐式接收this(作为参数)。静态方法不绑定到某个实例,所以你不能引用非静态字段。静态内容只能引用静态内容。

static可以用于:

  • 例如,用于单例模式;
  • 或者如果你想将类用作简单的_命名空间_;
  • 或者只是不喜欢面向对象编程(OOP)而打算使用面向过程编程(COP)。
英文:

According to the last question, you do not understand the difference. Every non-static method implicitly receives this (as an argument). Static methods are not bound to some instances, so you just can not reference non-static fields. Static stuff can reference only static stuff.

static could be used:

  • For Singleton pattern, for example;
  • Or if you want to utilize class as simple namespace;
  • Or just do not like OOP and going to use COP)

答案2

得分: 1

静态方法 Staf() 不允许返回类实例变量,因为可以在创建 Person 类实例之前调用 Staf()。因此,Staf() 只能返回静态变量。

英文:

The static method Staf() is not allowed to return class instance variables because Staf() can be invoked without the class Person instance being created. Therefore, Staf() can only return static variables.

答案3

得分: 0

你无法访问非静态(实例)变量,除非使用以下方式之一:a)引用一个实例(myPerson.isStaff,这将违反封装原则)或者b)从非静态(实例)方法内部访问。

至于何时应该使用static,这个问题在这个网站上有很多讨论和争论,可以轻松找到。

英文:

You can not access non-static (instance) variables unless you do so with a) a reference to an instance (myPerson.isStaff, which would violate encapsulation) or b) from within a non-static (instance) method.

As to when you should use static, there are many discussions and diatribes on this very website which can easily be found.

huangapple
  • 本文由 发表于 2020年8月7日 15:00:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63296750.html
匿名

发表评论

匿名网友

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

确定