问题描述:

I have the main class extends MapActivity, like this:

public class main extends MapActivity {

private MapView mapView;

......//something

public MapView getmapView() {

return mapView;

}

........//something

}

Why i couldn't access getmapView() method in another class,like this

MapView mv=main.getMapview()

网友答案:

You're confusing the syntax for accessing static methods with the syntax for accessing instance (i.e. non-static) methods.

Do you want each instance of your main class to have it's own MapView object, or do you want all of your main objects to share a single MapView?

If you want each instance of your main class to have it's own instance of MapView, then you need to call the getmapView() method on an instance of the main class, rather than on the name of the class itself:

main myObject = new main();
MapView mv=myObject.getmapView();

If instead you want all of your main objects to share a single MapView, then your getmapView() method and the mapView member itself need to be declared as static...

public class main extends MapActivity {
  private static MapView mapView;

  ......//something

  public static MapView getmapView() {
     return mapView;
  }

  ......//something
}

...then you can call the static getmapView() method using the line of code you already posted:

MapView mv=main.getMapview();

Further reading: take a look at this article in the Java tutorials for further explanation.

网友答案:

fisrt thing , if you want to access to your method using the name of your main class , your method should be a static method , and then you can do something like this :

MapView mv=main.getMapview(); 

and if you want to use it without static method, you should pass an instance of your main class to the other class .

if you want to use the static method then try this :

public class Main extends MapActivity {
    private static MapView mapView;

    ......//something

    public static MapView getmapView() {
        if(mapView == null)
               mapView = new MapView();
        return mapView;
    }
    ........//something
}

and in your second class you can simply use this :

MapView mv=Main.getMapview();
相关阅读:
Top