1

I cannot compile the code, below, because i have 17 errors regarding "non-static variable this cannot be referenced from a static context". It is always pointing at the this keyword.

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;
        }
    }
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216

3 Answers3

3

You cannot access non-static i.e. instance members from static init blocks or methods.

  • static is related to class and instance variables are related to instances of the class.
  • The reference of this means you are referring to the current object of class.
  • A static block is related to class so it does not have the information about the objects. So it cannot identify this.

In your example. you shoud make the method borrow non-static. It means they will relate to object of class and you can use this.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
2

In one sentence,

you cannot use "this keyword" inside a static context, such as static methods/static initializers.

PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

static variables are class wide. this is object wide. (in other words is reliant on an instance of the object) You have to instantiate an object to get access to this

The opposite is not true. You can access static variables from object instances

RNJ
  • 15,272
  • 18
  • 86
  • 131