-1
public class Canvas {
    public void erase(){}
}    

I want to use that erase method in another class but since it doesn´t appear to be static, I can´t just do this

public class Country {
    Canvas.erase();
}

So how do I access that method then?

4 Answers4

2

you'd need to create first an object (instance) of the class, and then call its methods, eg :

Canvas canvasInstance = new Canvas();
canvasInstance.erase();
nullPointer
  • 4,419
  • 1
  • 15
  • 27
1

Your only options is:

  1. Make the method static

    public static void erase(){}

  2. Call the method from an instance of Canvas

    new Canvas().erase();

André Paris
  • 139
  • 6
0

Non static method can be called with object refence only. Create an instance of Canvas class and then call erase method like,

Canvas canvas = new Canvas();
canvas.erase();
Vikas
  • 6,868
  • 4
  • 27
  • 41
0

The way I like to do it have a static reference of Canvas so this is how to do it:

public class Canvas
{
    public static Canvas cObj;

    public void erase() { }
} 


public class Country {

    public void CallMethod()
    {
        Canvas.cObj.erase();
    }
}

That way you would be able to call erase on Class Canvas easily from class County

Sachith Wickramaarachchi
  • 5,546
  • 6
  • 39
  • 68