如何在方法之间共享实例化对象?

时间:2014-07-02 17:55:39

标签: java object methods

我有:

public class HFSim extends ApplicationTemplate
{
  private static  class AppFrame extends ApplicationTemplate.AppFrame 
 {
     void setBuoy()
        {
            //code
                Position buoypos=Position.fromDegrees(buoylat, buoylon);
        }
    void setVehicle()
        { 
           //code
           Position vehiclepos=Position.fromDegrees(lat, lon, elev);
        }

    double findDistance() 
        {
        //find distance between marker (vehicle) and a buoy
        Earth earth= new Earth();
        double radius = earth.getEquatorialRadius();

        double distancebetween=LatLon.ellipsoidalDistance(buoypos, vehiclepos, radius, 6356752.3); 
        return distancebetween;
        }

如何在findDistance()方法的setBuoy和setVehicle方法中使用对象buoypos和vehiclepos?

3 个答案:

答案 0 :(得分:0)

使用类scope的变量。这基本上意味着

 ///outside of a method but within the class you'll want to set:
 private this.bouypos = new Position;
 private this vehiclepos = new Position;
 //method1 {
 Position this.buoypos=Position.fromDegrees(buoylat, buoylon);
 //method2 {
 Position this.vehiclepos=Position.fromDegrees(lat, lon, elev);
//method3 calls things set in method1 & 2
 findDistance(){
     //code
     double distancebetween=LatLon.ellipsoidalDistance(this.buoypos, this.vehiclepos, radius, 6356752.3); 
 }

答案 1 :(得分:0)

使findDistance方法将两个位置作为参数

double findDistance(Position buoypos, Position vehiclepos){

}

答案 2 :(得分:0)

这里有两个明确的选项:

  1. 制作buoypos和vehiclepos实例变量,或..
  2. 为setVehicle()提供更多描述性名称,并为其提供Position返回类型。
  3. 选项1看起来像这样:

    ...classname...
    {
        private Position vehiclePosition;
        private Position bouyPosition;
    
        public void setVehiclePosition()
        {
            this.vehiclePosition = ....
        }
    }
    

    选项2看起来像这样:

    ...classname...
    {
        public Position createVehiclePosition()
        {
            vehiclePosition = ....
            return vehiclePosition.
        }
    }
    

    最后,您可以将它们用作:

    ...classname...
    {
        public double findDistance()
        {
            ...this.vehiclePosition...
            or
            Position vehiclePos = this.createVehiclePosition();
        }
    }
    

    您选择的选项在很大程度上取决于课程的行为方式。