non-static method cannot be referenced from a static context (already created non-static, though)?

StackOverflow https://stackoverflow.com/questions/19895320

  •  30-07-2022
  •  | 
  •  

Question

I have a quick java question. Bear in mind I am a total newbie working through the lowest level programming class I could find. I have an assignment that I'm working on but I'm having a problem with a specific part of it. I've snipped the code down to the core and I still can't find out what I am doing wrong with it. I would appreciate any help with this.

First I have created a class ("Car"). This class has a constructor that takes an argument. (again this has been snipped a lot, it's longer but the error persists with just this code):

public class Car
{
   private String make;

   public Car(String carMake)
   {
      make = carMake;
   }

   public String getMake()
   {
      return make;
   }
}

This part compiles with no problem. When I try to use this class in a main class, though, that's where things go wrong and I encounter an error.

public class Drive
{
   public static void main(String[] args)
   {
      Car userCar;

      userCar = new Car("Focus");

      System.out.println(Car.getMake());
   }
}

Compiling this class gives me this error message.

Drive.java:9: error: non-static method getMake() cannot be referenced from 
a static context
  System.out.println(Car.getMake());

I've done a lot of searching over the Internet and SE for this and nearly ever instance of this I found happening was because the coder did not "create" the non-static part. I have done this, though. I can't seem to figure out what I'm doing wrong. If anyone could help me understand my fault I would greatly appreciate it.

Thanks!

Was it helpful?

Solution

getMake() is not static, so you need to access it for a single instance of Car at a time. So change your code to userCar.getMake(). This means that you want to get the make of userCar, which is an actual object instance.

In constrast, calling Car.getMake() doesn't make conceptual sense, because there is no single make for every single Car in the world. Only individual cars such as userCar have a make, model, etc.

OTHER TIPS

Do this:

userCar.getMake();

i.e. getMake() is not a static method so you need to call this by instance of the class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top