非静态变量,不能从静态上下文引用

时间:2013-07-23 15:25:26

标签: java

我是java的初学者 我无法编译下面的代码,因为我有17个关于“无法从静态上下文中引用的非静态变量”的错误。 它始终指向“这个”。声明。 我是学生

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;
        }
    }
}

3 个答案:

答案 0 :(得分:2)

用一句话,

  

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

答案 1 :(得分:2)

您无法从静态init块或方法访问非静态实例成员。

  • static与类相关,实例变量与类的实例相关。
  • this的引用意味着您指的是当前的类对象。
  • 静态块与类相关,因此它没有关于对象的信息。因此无法识别this

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

答案 2 :(得分:1)

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

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

相关问题