2013-07-23 110 views
1

我是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; 
     } 
    } 
} 
+6

哇,自从这个问题出现在'SO'后只有5分钟 – Reimeus

+0

您的借用方法是否需要静态?我觉得使它非静态可以解决你的问题... – StephenTG

+1

让你觉得也许java IDE可能会提醒你。 – sje397

回答

2

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

  • static与类和实例变量有关,与类的实例有关。
  • this的引用意味着您引用了当前类的对象。
  • 静态块与类相关,因此它没有关于对象的信息。所以它不能识别this

在你的例子中。你应该使方法borrow非静态。这意味着他们将涉及到课堂的对象,你可以使用this

2

在一个句子,

不能使用"this keyword"一个静态的上下文中,如静态方法/静态初始化。

+0

这正是错误所说的,尽管.. – arshajii

1

静态变量是类宽的。 这个是对象广泛的。 (换句话说依赖于对象的一个​​实例)你必须实例化一个对象才能访问这个

相反是不正确的。您可以从对象实例访问静态变量

相关问题