简体   繁体   English

通过对象在静态方法上使用非静态变量? Java的

[英]Using a non static variable on a static method through an object? Java

Since we can't use this inside a static method, and we also cannot use non-static variables, why is it that we can use objects, which use nonstatic variables inside static methods? 既然我们不能在静态方法中使用this ,并且我们也不能使用非静态变量,为什么我们可以使用在静态方法中使用非静态变量的对象呢?

Here is what I mean: 这就是我的意思:

public int x;
public int y;

public Account(int a, int b) {
    this.x = a;
    this.y = b;
}

public static void Swap(Account acc) {
    int holder;
    holder = acc.x;
    acc.x = acc.y;
    acc.y = holder;
}

So Swap() will work, even though the variables inside of the object are not static. 因此Swap()将起作用,即使对象内部的变量不是静态的。 I don't understand this part. 我不明白这一部分。 Would appreciate some help. 会感激一些帮助。 TIA! TIA!

static methods cannot access instance variable of the current ( this ) instance, since no such instance exists in their context. static方法无法访问当前( this )实例的实例变量,因为在其上下文中不存在此类实例。

However, if you pass to them a reference to an instance, they can access any instance variables and methods visible to them. 但是,如果向它们传递对实例的引用,则它们可以访问对它们可见的任何实例变量和方法。

In case of your swap example, if that method wasn't static , you could have removed the acc argument and operate on the instance variables of this : 如果你的swap示例,如果该方法不是static ,你可以删除acc参数并this实例变量进行操作:

public void swap() {
    int holder;
    holder = this.x;
    this.x = this.y;
    this.y = holder;
}

You cannot use this in a static method because Java does not know which instance (which this) you refer to. 您不能在静态方法中使用this ,因为Java不知道您引用的是哪个实例(这个)。

You can pass a reference to an object as a parameter acc to a static method because the caller specifies which instance to pass. 可以传递给一个对象作为参数的引用acc因为调用者指定传递该实例的静态方法。

Java knows which instance you mean when your static method refers to acc . 当静态方法引用acc时,Java知道你指的是哪个实例。 So you can use any accessible fields or methods of acc . 因此,您可以使用任何可访问的字段或acc方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM