我是面向對象編程的初學者,我需要一些答案來清除一些東西。我有一個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對象嗎?如果我沒有通過藍牙服務對象,藍牙可能無法工作?在GPS類中,我無法創建新的BluetoothService連接對象並將其傳遞給Nmea構造函數,因爲我只需要在整個項目中建立一個連接。
GPS類:
public çlass GPS {
Nmea gpsNmea = new Nmea();
//I need to use Nmea methods here
}
我希望你明白我的問題。用這些東西來實現它的好方法是什麼? 謝謝!
如果您的方法是公開的,您可以使用點符號訪問它! gpsNmea.yourMethod();如果你沒有指定任何修飾符,你將得到默認修飾符(public爲你包中的所有元素,private爲其他包中的元素) – GVillani82 2013-05-11 12:36:01