Home > Mobile >  x cannot be resolved or is not a field y cannot be resolved or is not a field
x cannot be resolved or is not a field y cannot be resolved or is not a field

Time:12-03

Main:

public class Main {
    public static void main(String [] args) {
        Foo<String, Location> foo = new Foo<>();
        foo.add("abc", new Location(5, 6));
    }
}

Location:

public class Location {
    public int x;
    public int y;

    public Location(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "("   x   ","   y   ")";
    }
}

Foo class:

public class Foo<K, T> {
    
    public void add(K name, T loc) {
        System.out.println(name   " "   loc.x   loc.y);
    }
    
    
}

When I try to run the program I get the "question title" error, I don't know what that happens, and how to fix that.

CodePudding user response:

One way is to use instanceof operator if you are expecting a type that you know. This is a demo.

public void add(K name, T loc) {
    if(loc instanceof Location) {
        System.out.println(name   " "   ((Location)loc).x   ((Location)loc).y);
    }
}
  • Related