对创建对象和使用其方法感到困惑

时间:2013-05-11 12:20:56

标签: java

我是面向对象编程的初学者,我需要很少的答案来清除一些东西。我有一个MainActivity和几个类用于不同的操作。例如,在MainActivity中,我从BluetoothReceiver类创建一个名为mBluetoothReceiver的对象。有建立和管理BT连接的方法,例如sendData。在Nmea类中,我得到了一些使用BluetoothReceiver方法的方法,因此我通过构造函数mBluetoothReceiver。

MainActivity类:

public class MainActivity extends Activity {

    BluetoothService mBluetoothService = new BluetoothService(this);

    //create new object from Nmea class and pass mBluetoothService to mNmea
    Nmea mNmea = new Nmea(mBluetoothService);
}

Nmea班:

public class Nmea {

BluetoothService mBluetoothService;

    //constructor for Nmea for BluetoothServce object
    public Nmea(BluetoothService bluetoothService) {
        mBluetoothService = bluetoothService;
    }

    public Nmea()
    {
    //empty constructor {

    }

    //Nmea methods...
}

我的问题是,我还有GPS类,它也会使用Nmea类的方法,但我不知道该怎么做。可以在Nmea类中放置空构造函数并在GPS类中创建Nmea对象吗?如果我不通过BluetoothService对象,蓝牙可能无法正常工作?在类GPS中,我无法创建新的BluetoothService连接对象并将其传递给Nmea构造函数,因为我在整个项目中只需要一个已建立的连接。

GPS等级:

public çlass GPS {

Nmea gpsNmea = new Nmea();

//I need to use Nmea methods here

}

我希望你理解我的问题。什么是这个东西的好实践,以获得工作呢? 谢谢!

3 个答案:

答案 0 :(得分:1)

访问类方法

根据方法access modifier,您可以使用.运算符来获取方法。像这样:

String s = "Hello";
s = s.substring(0,3); // See how you use the ".", then the name of the method.

您的其他疑问

  

可以在Nmea类中放置空构造函数并在GPS类中创建Nmea对象吗?

没有价值。如果你没有明确地写一个,Java将提供default constructor

  

在GPS课程中,我无法创建新的BluetoothService连接对象并将其传递给Nmea构造函数,因为我在整个项目中只需要一个已建立的连接。

然后,您需要将处理BluetoothService对象的类转换为单例。你可以阅读有关单身人士here的内容。使用单例模式,您可以静态访问对象,而无需始终创建新对象。

例如

public abstract class BluetoothSingleton
{
    private static BluetoothService instance;
    // The one instance of BluetoohService that will be created.

    public static BluetoothService getInstance()
    {
        if(instance == null)
        {
            // If an object doesn't currently exist.
            instance = new BluetoothService(); // or whatever you're using.
        }
        return instance;
    }
}

然后,当您希望获得BluetoothService个对象时,只需调用getInstance()类中的BluetoothSingleton方法。

BluetoothService = BluetoothSingleton.getInstance();
// This code will return the exact same instance. Only one will ever be created. 

答案 1 :(得分:1)

你可以这样写:

public class MainActivity extends Activity {
    BluetoothService mBluetoothService = new BlueToothService(this);

    Nmea mNmea = new Nmea(mBluetoothService);

    Gps mGps = new Gps(mNmea);     
}

你的Gps cconstructor需要看起来像这样:

public class Gps {

    private Nmea mNmea;

    public Gps(Nmea nmea) {
        mNmea = nmea;
    }
}

如果您只需要一个BluetoothService课程实例,则需要使用Singleton design pattern来编写他,并且Nmea类中所有需要的方法都声明为public

答案 2 :(得分:0)

您可以在Nmea中使用GPS类的实例来使用Nmea的方法。只需将其添加到gpsNmea.any_Nmea_function()类内的代码GPS,例如:

public çlass GPS {

Nmea gpsNmea = new Nmea();

gpsNmea.getN(); //assuming getN() is a function defined in Nmea class.

}

.运算符允许您访问类实例变量的成员方法或变量。

相关问题