2017-07-09 60 views
0

的一個對象,我有兩個班做同樣的事情,但通過不同的方式。我需要根據配置設置創建其中一個類的對象。以下是我想要做什麼的簡單示例。的Android創建類似的類

public class A { 
    public string getLetter() { 
     return "A"; 
    } 
} 
public class B { 
    public string getLetter() { 
     return "B"; 
    } 
} 

public class MainActivity { 
    private myObject; // How to declare it in my case? 
    private int config = 0; 

    public void onCreate(Bundle savedInstanceState) { 
     if (config == 0) { 
      myObject = new A(); 
     } else { 
      myObject = new B(); 
     } 
     String letter = myObject.getLetter(); 
    } 
} 

其實一切都複雜得多。每個類A和B的異步偵聽數據的不同的來源,將其轉換爲可在進一步的處理中使用,並將其傳遞到MainActivity的格式。根據配置,只能選擇一個數據源。我怎樣才能做到這一點?與

letter = A.getLetter(); 

將不起作用。

回答

0

這應該工作:

public class A { 
    public String getLetter() { 
     return "A"; 
    } 
} 
public class B { 
    public String getLetter() { 
     return "B"; 
    } 
} 

public class MainActivity { 


    private int config = 0; 

    public void onCreate(Bundle savedInstanceState) { 


     String letter=""; 
     if (config == 0) { 
      A myObject = new A(); 
      letter = myObject.getLetter(); 
     } else { 
      B myObject = new B(); 
      letter = myObject.getLetter(); 
     } 


    } 
} 
0

使用interfaceabstract class和執行或者它在A類和B,例如延伸

public interface Letter { 
    String getLetter(); 
} 
public class A implements Letter { 
    public String getLetter() { 
     return "A"; 
    } 
} 
public class B implements Letter { 
    public String getLetter() { 
     return "B"; 
    } 
} 


// Then you can declare and use it as interface 
private Letter myObject; 

// init logic 
... 
String letter = myObject.getLetter();