-2

car.java

package com.krishna;

public class car {
    private int door;
    private int wheels;
    private String model;
    private String engine;
    private String colour;

    public void setModel(String model)
    {
        String validModel=model.toLowerCase();
        if(validModel=="krish"||validModel=="raju")
        {
            this.model = model;
        }
        else
        {
            this.model="unknown";
        }
    }

    public static String getModel()
    {
        return this.model;
    }
}

Main.java

package com.krishna;

public class Main {

    public static void main(String[] args) {
    // write your code here
        car obj1=new car();
        car obj2=new car();
        obj1.setModel("krish");
        System.out.println(obj1.getModel());
    }
}

static function cannot reference with this keword in java

TDG
  • 5,909
  • 3
  • 30
  • 51
user8576367
  • 207
  • 3
  • 14
  • first of all, ask yourself: what object is `this` in `getModel()` method? And what object is `this` in `setModel()`? Hint: `getModel()` has `static` modifier, whilst `setModel()` hasn't. – hoefling Sep 16 '17 at 10:11
  • Not really what you asked but `if(validModel=="krish"||validModel=="raju")` -> [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Pshemo Sep 16 '17 at 10:17
  • Also there is no `this` in static context. `static` means that member (method here) belongs to entire class, not specific instance. – Pshemo Sep 16 '17 at 10:18

1 Answers1

1

Static methods belong to the class not objects of that class. Remove static keyword from static String getModel() for this to work.

Manoj Suthar
  • 1,415
  • 3
  • 19
  • 41