非静态方法可以修改静态变量 [英] Can non-static methods modify static variables

查看:1082
本文介绍了非静态方法可以修改静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道非静态方法如何修改静态实例变量。我知道静态方法只能访问其他静态方法和静态变量。但是,另一方是真的吗?非静态方法可以只访问非静态变量吗?例如:

I am wondering how a non static method can modify a static instance variable. I know that static methods can only access other static methods and static variables. However, is the other side true? Can non-static methods access only non-static variables? For example:

public class SampleClass {
  private static int currentCount = 0;

  public SampleClass() {
    currentCount++;
  }

  public void increaseCount() {
    currentCount++;
  }
}

此代码编译,我想知道为什么在静态访问权限的条款。

This code compiles and I would like to know why in terms of static access privledges.

推荐答案

我是从 Java教程


  • 实例方法可以访问实例变量和实例方法直接。

  • 实例方法可以直接访问类变量和类方法。

  • 类方法可以访问类变量和类方法直接。

  • 类方法不能直接访问实例变量或实例方法 - 它们必须使用对象引用。此外,类方法不能使用this关键字,因为没有实例可以引用它。

  • Instance methods can access instance variables and instance methods directly.
  • Instance methods can access class variables and class methods directly.
  • Class methods can access class variables and class methods directly.
  • Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.

所以答案是肯定的,非-static方法可以修改静态变量

So the answer is yes, non-static methods CAN modify static variables

这篇关于非静态方法可以修改静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆