什么时候该用成员变量、什么时候用方法变量?

来源:互联网 发布:linux 修改主机名 编辑:程序博客网 时间:2024/05/21 08:38

Use class level field or method variable?(什么时候该用成员变量、什么时候用方法变量?)

  1. If it’s strongly associated with the class, make it static.
  2. If it’s strongly associated with an instance, make it a non–static member.
  3. If it’s strongly associated with a method invocation, or the current thread, or you can’t decide about (1) or (2), make it method-local.

Note: 这是SO的一个回答,以后再思考这个问题。

UPDATE :

  • 2017-03-04: 对于Java来说,对象是抽象的,将一系列的member和行为组装起来,所以在区分class变量和方法局部变量就很容易。然后另外class的变量的作用是共享,如果是可以被其他类或本Class中的其他方法所共享的,那么就应该是类变量。
0 0
原创粉丝点击