【问题标题】:non-static variable this cannot be referenced from a static context [duplicate]非静态变量 this 不能从静态上下文中引用[重复]
【发布时间】:2013-07-23 15:25:25
【问题描述】:

我无法编译下面的代码,因为我有 17 个关于“无法从静态上下文引用的非静态变量”的错误。 它总是指向this 关键字。

package MyLib;
import java.util.*;

class Book {

static int pages;
static String Title;
static String Author;
static int status;
static String BorrowedBy;
static Date ReturnDate;
static Date DueDate;

public static final int
    BORROWED = 0;

public static final int
    AVAILABLE = 1;

public static final int
    RESERVED = 2;

    //constructor
public Book ( String Title, String Author, int pp) {
    this.Title = Title;
    this.Author = Author;
    this.pages = pp;
    this.status = this.AVAILABLE;
}

public static void borrow(String Borrower/*, Date Due*/){
    if (this.status=this.AVAILABLE){
        this.BorrowedBy=Borrower;
        this.DueDate=Due;
    
    }
    else {
    
        if(this.status == this.RESERVED && this.ReservedBy == Borrower){
            this.BorrowedBy= Borrower;
            this.DueDate=Due;
            this.ReservedBy="";
            this.status=this.BORROWED;
        }
    }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    您不能从静态初始化块或方法访问非静态,即实例成员。

    • 静态与类相关,实例变量与类的实例相关。
    • this 的引用表示您正在引用类的当前对象。
    • 静态块与类相关,因此它没有关于对象的信息。所以它无法识别this

    在你的例子中。您应该使方法borrow 非静态。这意味着它们将与类的对象相关,您可以使用this

    【讨论】:

      【解决方案2】:

      一句话,

      您不能在静态上下文中使用 "this keyword",例如静态方法/静态初始化器。

      【讨论】:

        【解决方案3】:

        静态变量是类范围的。 this 是对象范围的。 (换句话说,依赖于对象的实例)您必须实例化一个对象才能访问 this

        反之则不然。您可以从对象实例中访问静态变量

        【讨论】:

          猜你喜欢
          • 2013-04-04
          • 1970-01-01
          • 2011-05-12
          • 2013-12-02
          • 2013-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多