sách gpt4 ai đã đi

Java: static-non-static-这个问题

In lại 作者:行者123 更新时间:2023-12-04 05:50:17 26 4
mua khóa gpt4 Nike

$ 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 files = new HashSet();
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);
}
}
}

更新:定义“当前对象”

构造函数已创建,对象已创建,但cái này 未引用当前对象“测试”。当我将其更改为“测试”时它有效,但它不适用于“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 files;

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

TestFilter(){
files = new HashSet();
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 getFiles() { return files; }
}

1 Câu trả lời

关键字 cái này 引用当前的 sự vật -- 你没有的东西,因为你的方法是静态的。这意味着它在类本身上运行,而不是在任何对象上运行,因此对 cái này 的任何使用都是无效的——mặc dù您尝试访问的特定变量是静态的也。访问静态成员的正确方法是通过类:TestFilter.filterFiles, thay vì this.filterFiles.

关于Java: static-non-static-这个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2625031/

26 4 0
Bài viết được đề xuất: hibernate - 带有 JPA 2.1 的 Websphere 8.5
Bài viết được đề xuất: php - 需要 Google 地理编码返回英文城市名称
Bài viết được đề xuất: php - 递归函数
Bài viết được đề xuất: ruby-on-rails - Rails/Devise-NoMethodError(针对#的未定义方法new_with_session')
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com