Java:静态-非静态-这个问题

发布于 2024-08-28 05:49:25 字数 2801 浏览 10 评论 0原文

$ javac TestFilter.java 
TestFilter.java:19: non-static variable this cannot be referenced from a static context
        for(File f : file.listFiles(this.filterFiles)){
                                    ^
1 error
$ sed -i 's@this@TestFilter@g' TestFilter.java 
$ javac TestFilter.java 
$ java TestFilter
file1
file2
file3

TestFilter.java

import java.io.*;
import java.util.*;

public class TestFilter {
    private static final FileFilter filterFiles;

    // STATIC!
    static{
        filterFiles = new FileFilter() {
            // Not Static below. When static, an error:
            // "accept(java.io.File) in  cannot implement 
            // accept(java.io.File) in java.io.FileFilter; 
            // overriding method is static"
            //
            // I tried to solve by the change the problem at the bottom.

            public boolean accept(File file) {
                return file.isFile();
            }
        };
    }

   // STATIC!
    public static void main(String[] args){
        HashSet<File> files = new HashSet<File>();
        File file = new File(".");

            // IT DID NOT WORK WITH "This" but with "TestFilter".
            // Why do I get the error with "This" but not with "TestFilter"?

        for(File f : file.listFiles(TestFilter.filterFiles)){
            System.out.println(f.getName());
            files.add(f);
        }
    }
}

更新:定义“当前对象”

创建构造函数,创建对象,但 this 不引用当前对象< /em>“测试”。当我将其更改为“test”时它可以工作,但它不适用于“this”。为什么?

$ javac TestFilter.java 
TestFilter.java:28: non-static variable this cannot be referenced from a static context
        for(File f : this.getFiles()){
                     ^
1 error
$ cat TestFilter.java 
import java.io.*;
import java.util.*;

public class TestFilter {

    private static final FileFilter filterFiles;
    private HashSet<File> files;

    static{
        filterFiles = new FileFilter() {
            public boolean accept(File file) {
                return file.isFile();
            }
        };
    }

    TestFilter(){
        files = new HashSet<File>();
        File file = new File(".");

        for(File f : file.listFiles(filterFiles)){
            files.add(f);
        }
    }

    public static void main(String[] args){

        // CONSTRUCTOR with no pars invoked and object "test" created here!

        TestFilter test = new TestFilter();

        // Why does it not work with "this"? 
        // "test" is surely the current object.

        for(File f : this.getFiles()){
            System.out.println(f.getName());    
        }
    }

    public HashSet<File> getFiles() { return files; }
}
$ javac TestFilter.java 
TestFilter.java:19: non-static variable this cannot be referenced from a static context
        for(File f : file.listFiles(this.filterFiles)){
                                    ^
1 error
$ sed -i 's@this@TestFilter@g' TestFilter.java 
$ javac TestFilter.java 
$ java TestFilter
file1
file2
file3

TestFilter.java

import java.io.*;
import java.util.*;

public class TestFilter {
    private static final FileFilter filterFiles;

    // STATIC!
    static{
        filterFiles = new FileFilter() {
            // Not Static below. When static, an error:
            // "accept(java.io.File) in  cannot implement 
            // accept(java.io.File) in java.io.FileFilter; 
            // overriding method is static"
            //
            // I tried to solve by the change the problem at the bottom.

            public boolean accept(File file) {
                return file.isFile();
            }
        };
    }

   // STATIC!
    public static void main(String[] args){
        HashSet<File> files = new HashSet<File>();
        File file = new File(".");

            // IT DID NOT WORK WITH "This" but with "TestFilter".
            // Why do I get the error with "This" but not with "TestFilter"?

        for(File f : file.listFiles(TestFilter.filterFiles)){
            System.out.println(f.getName());
            files.add(f);
        }
    }
}

Update: define "current object"

Constructor created, object created but the this does not refer to the current object "test". It works when I change this to "test" but it does not work with "this". Why?

$ javac TestFilter.java 
TestFilter.java:28: non-static variable this cannot be referenced from a static context
        for(File f : this.getFiles()){
                     ^
1 error
$ cat TestFilter.java 
import java.io.*;
import java.util.*;

public class TestFilter {

    private static final FileFilter filterFiles;
    private HashSet<File> files;

    static{
        filterFiles = new FileFilter() {
            public boolean accept(File file) {
                return file.isFile();
            }
        };
    }

    TestFilter(){
        files = new HashSet<File>();
        File file = new File(".");

        for(File f : file.listFiles(filterFiles)){
            files.add(f);
        }
    }

    public static void main(String[] args){

        // CONSTRUCTOR with no pars invoked and object "test" created here!

        TestFilter test = new TestFilter();

        // Why does it not work with "this"? 
        // "test" is surely the current object.

        for(File f : this.getFiles()){
            System.out.println(f.getName());    
        }
    }

    public HashSet<File> getFiles() { return files; }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

倾听心声的旋律 2024-09-04 05:49:25

关键字 this 引用当前的对象——您没有的东西,因为您的方法是静态的。这意味着它在类本身上运行,而不是在任何对象上运行,因此任何 this 的使用都是无效的 - 即使您尝试访问的特定变量是静态的也。访问静态成员的正确方法是通过类:TestFilter.filterFiles,而不是this.filterFiles

The keyword this refers to the current object -- something that you don't have, because your method is static. That means it's running on the class itself, not on any object, so any use of this is invalid -- even though the specific variable you're trying to access is static too. The correct way to access a static member is by the class: TestFilter.filterFiles, not this.filterFiles.

梦魇绽荼蘼 2024-09-04 05:49:25

为什么“this”会出现错误,而“TestFilter”却不会出现错误?

  • this 用于引用“实例”属性或方法(除其他外) 。实例意味着存在一个新对象,并且每个对象(实例)都有给定属性的副本。

  • 类名(在您的例子中是TestFilter)用于引用“类”属性或方法(那些不需要实例存在的属性或方法。

因此,在在第一行中,您将 filterFiles 声明为类属性(您不需要为此提供实例。

请参阅:

private static final FileFilter filterFiles;

这意味着,您声明名为:class 的属性>filterFiles 类型为 FileFilter,它是 private 并且其引用不能更改(因为它是 final

。是一个 class 属性,您可以在 main 方法中访问它(这是一个类级别的方法)。这两者都可以工作:

for(File f : file.listFiles(TestFilter.filterFiles)){

for(File f : file.listFiles(filterFiles)){

不会

for(File f : file.listFiles(this.filterFiles)){

,因为 this 指的是当前实例,但由于您处于类级方法 ( main ) 中,因此没有实例,因此,没有 this 或编译器的话:非静态变量 this 不能从静态上下文引用

实例属性对于每个实例都是唯一的。类级别属性对于每个类都是唯一的。

考虑以下课程:

import static java.lang.System.out;
class Employee  {
     // class level counter. It exist regardless of the instances created.
     public static int employeeCount = 0;
     // instance attribute. Each one is different from others instances
     private String employeeName;

     // Class level method, can be invoked without instance.
     public static Employee createEmployee( String withName ) {

         Employee e = new Employee();
         // Set the name to the instance
         e.employeeName = withName;
         // Increments the class counter
         Employee.employeeCount++;
         return e;
     }
     // Object constructor.
     public Employee() {
          out.println("Constructor invoked!!! A new object has born, yeah!");
     }
     // Instance method "toString()"
     public String toString() {
         // Uses "this" to refer instance level method
         return this.emploeeName;
     }

     // Test
     public static void main( String [] args ) {

          // The counter already exist
          out.printf("Employees created %d%n", Employee.employeeCount );
          // Create employee a
          Employee a = Employee.createEmployee("Oscar");
          // Its name now exists 
          out.printf("Employee name: %s %nEmployees created %d%n",
                      a.employeeName,  Employee.employeeCount );
          // Create employee b with a new name 
          Employee b = Employee.createEmployee("HH");
          out.printf("Employee name: %s %nEmployees created %d%n", 
                      b.employeeName,  Employee.employeeCount );
          // Now both employees exist, each one with a name 
          out.printf("a=%s, b=%s%n, a, b );// invoke toString method which in turn uses "this"

     }
}

我希望这个示例能让一切变得清晰。

Why do I get the error with "this" but not with "TestFilter"?

  • this is used to refer to "instance" attributes or method ( among others ). Instance means a new object exist and each object ( instance ) have a copy of the given attribute.

  • The class name ( in your case TestFilter ) is used to refer to "class" attributes or methods ( those who do not require an instance to extist.

So, in your first line you're declaring filterFiles as a class attribute ( you don't require an instance for that.

See:

private static final FileFilter filterFiles;

This means, you declare class attribute named: filterFiles of type FileFilter which is private and whose reference can't be changed ( because it is final).

Since it is a class attribute you may access it in the main method ( which is a class level method ). This both will work:

for(File f : file.listFiles(TestFilter.filterFiles)){

and

for(File f : file.listFiles(filterFiles)){

But

for(File f : file.listFiles(this.filterFiles)){

Won't, because this refers to the current instance, but since you're in a class level method ( main ) there is no instance, so, there is no this or in compiler words: non-static variable this cannot be referenced from a static context

Instance attributes are unique per instance. Class level attribute are unique per class.

Consider the following class:

import static java.lang.System.out;
class Employee  {
     // class level counter. It exist regardless of the instances created.
     public static int employeeCount = 0;
     // instance attribute. Each one is different from others instances
     private String employeeName;

     // Class level method, can be invoked without instance.
     public static Employee createEmployee( String withName ) {

         Employee e = new Employee();
         // Set the name to the instance
         e.employeeName = withName;
         // Increments the class counter
         Employee.employeeCount++;
         return e;
     }
     // Object constructor.
     public Employee() {
          out.println("Constructor invoked!!! A new object has born, yeah!");
     }
     // Instance method "toString()"
     public String toString() {
         // Uses "this" to refer instance level method
         return this.emploeeName;
     }

     // Test
     public static void main( String [] args ) {

          // The counter already exist
          out.printf("Employees created %d%n", Employee.employeeCount );
          // Create employee a
          Employee a = Employee.createEmployee("Oscar");
          // Its name now exists 
          out.printf("Employee name: %s %nEmployees created %d%n",
                      a.employeeName,  Employee.employeeCount );
          // Create employee b with a new name 
          Employee b = Employee.createEmployee("HH");
          out.printf("Employee name: %s %nEmployees created %d%n", 
                      b.employeeName,  Employee.employeeCount );
          // Now both employees exist, each one with a name 
          out.printf("a=%s, b=%s%n, a, b );// invoke toString method which in turn uses "this"

     }
}

I hope this sample make everything clear.

荒芜了季节 2024-09-04 05:49:25

您不能在静态函数中引用实例变量,例如“this”指针。由于 TestFilter 是类,并且 filterFiles 变量是静态的,因此它可以工作,因为您可以在静态函数中使用静态变量。

如果 TestFilter 应该实例化为类,我建议将 main 函数内的代码移至构造函数。在这种情况下,您将能够访问“this”。

you cannot reference instance variables like the "this" pointer in static functions. Since TestFilter is the class and the filterFiles variable is static, it works, because you can use static vars in static functions.

If TestFilter is something that is supposed to be instantiated as a class, I suggest moving the code inside the main function to the constructor. In that case, you would be able to access "this".

仅冇旳回忆 2024-09-04 05:49:25

这是对实际使用的对象实例的引用。在静态方法中,该类未实例化 - 这在此上下文中没有任何意义。

this is a reference to the instance of the object actually used. In a static method the class wasn't instantiated - this has no meaning in this context.

你的笑 2024-09-04 05:49:25

静态成员由类引用,而不是由实例引用。这意味着您必须使用类名来引用静态成员,而不是实例名。

因为 this 引用一个实例,所以您会收到编译错误。

Static members are referenced by Class, not by instance. What this means is that you must use class name to reference the static member, not instance name.

Because this refers to an instance, you get compile error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文