Home > IB Computer Science 2016, IB Computer Science 2017 > Three ways round the “non-static method cannot be referenced from a static context” problem…

Three ways round the “non-static method cannot be referenced from a static context” problem…

The problem occurs when you try to do this:

public class Dog {
  public static void main(String args[]){
    bark(); 
    // ERROR: non-static method cannot be referenced
    // from a static context
  }
  void bark() {
    System.out.println("Woof");
  }
}

Java is telling us that you cannot call bark() if you haven’t got a dog!

The solution is to instantiate a Dog before you call the bark() method, or… and this is the really lazy method… just declare your bark() method static, so that it doesn’t need an instance.

Solution 1: Two classes

public class DogMain {
  public static void main(String args[]){
    Dog d = new Dog();
    d.bark();
  }
}
class Dog {
  void bark() {
    System.out.println("Woof");
  }
}

Solution 2: Self-instantiating class

public class Dog {
  public static void main(String args[]){
    Dog d = new Dog();
    d.bark();
  }
  void bark() {
    System.out.println("Woof");
  }
}

Solution 3: Lazy cop-out

public class Dog {
  public static void main(String args[]){
    bark();
  }
  static void bark() {
    System.out.println("Woof");
  }
}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s