2014-08-30 2 views
0

방금 ​​이번 여름에 일부 자바 클래스를 가져 왔고 모든 것이 잘 진행되었지만 막혔습니다. 인터페이스. 나는 인터페이스를 사용하여 파일과 같은 클래스로 메서드를 그룹화 할 수 있지만 실제로 프로그래밍 할 때는 언제 사용해야하는지 알 수 있습니다. 나는 약간 혼란 스럽다. 정의가있는 예제가 있습니다.자바에서 인터페이스를 사용하는 이유는 무엇입니까?

+0

에 약간의 통찰력을 제공 희망 읽기 'Interface'은 너무 응용 프로그래밍 인터페이스 (API)에서 사용할 수 있습니다. – Spurdow

답변

0

제 생각에는 인터페이스는 특정 시간에 수행 할 작업을 나타냅니다.

예를 들어 하드웨어 키를 누르면 onKeyDown 인터페이스가 호출됩니다. 여기서 "누르십시오"는 특정 시간입니다. 그 때 우리는 무엇을해야합니까? onKeyDown으로 전화하면됩니다.

또 다른 장점은 인터페이스를 통해 실제 클래스 인스턴스가 무엇인지 알 필요가 없다는 것입니다. 호출 할 수있는 메서드가 있다는 것을 알면 충분합니다.

3

인터페이스는 파일

인터페이스는 계약입니다 같은 클래스 그룹 최대 방법으로 우리를 할 수 있습니다. 구현이 부족하고, 방법이 부족합니다. 그러나 그것은 무엇을 지정합니다.

이점은 인터페이스를 사용하는 모든 장소에 변경 사항을 종속 연결하지 않고도 다른 구현 (또는 솔루션)을 교환 할 수 있다는 것입니다.

예를 들어, JDK 라이브러리를 살펴보십시오. 그들은 List 인터페이스와 다른 상황에서 더 나은 다른 구현을 제공하는 몇 가지 다른 구현을 제공합니다. 예를 들어, LinkedList와 ArrayList는 모두 List를 구현하지만 매우 다른 수행을합니다. 때로는 LinkedList가 ArrayList보다 낫고, 그 반대의 경우는 true입니다.

1

하지만 실제 프로그래밍에서는 언제 사용해야합니까? 나를 위해

내가 항상 사용하는 가장 간단하고 가장 좋은 방법은 여기에 callback pattern

interface CallBack { 
    void methodToCallBack(); 
} 

class CallBackImpl implements CallBack { 
    public void methodToCallBack() { 
     System.out.println("I've been called back"); 
    } 
} 

class Caller { 

    public void register(CallBack callback) { 
     callback.methodToCallBack(); 
    } 

    public static void main(String[] args) { 
     Caller caller = new Caller(); 
     CallBack callBack = new CallBackImpl(); 
     caller.register(callBack); 
    } 
} 

의 간단한 예는이 Listener

대부분의 경우에 사용되어있는 callback pattern입니다 보다 구체적인 방법은 다음과 같습니다.

// Reverse geocoding may take a long time to return so we put it in AsyncTask. 
public class ReverseGeocoderTask extends AsyncTask<Void, Void, List<Address>> { 
    private static final String TAG = "ReverseGeocoder"; 

    private Geocoder mGeocoder; 
    private float mLat; 
    private float mLng; 
    private Callback mCallback; 
    public ReverseGeocoderTask(Geocoder geocoder, float[] latlng, 
      Callback callback) { 
     mGeocoder = geocoder; 
     mLat = latlng[0]; 
     mLng = latlng[1]; 
     mCallback = callback; 
    } 
    @Override 
    protected List<Address> doInBackground(Void... params) { 
     List<Address> address = null; 
     try { 
      List<Address> address = 
        mGeocoder.getFromLocation(mLat, mLng, 1); 

     } catch (Exception ex) { 
      // ignore 
     } 
     return address; 
    } 
    @Override 
    protected void onPostExecute(List<Address> address) { 
     if(address != null) 
      mCallback.onComplete(address); 
    } 
} 

// the interface 
public interface Callback { 
    public void onComplete(List<Address> address); 
} 

// example fragment 

public class MyCallbackFragment extends Fragment implements Callback{ 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.fragment_layout); 
     // params the geocoder, float[] latlng, and the class that implements Callback 
     new ReverseGeocoderTask(new Geocoder(getActivity(), Locale.getDefault()) , latlng, this).execute(null,null,null); 
    } 
    ... 

    @Override 
    public void onComplete(List<Address> address){ 
     // now we can get the address not interupting the main thread 
     // and also let the Task call us back to retrieve the information 
     // and use it. 

     // you can then use the address to display it anywhere you want in your UI 



    } 
} 
나는 택시/택시 앱의 지리적 위치에 대해 이런 종류의 패턴을 사용 했으므로 직접 가져 오지 말고 전화를 걸고 null이 아닌 경우 필요한 것을 보내주세요.

이것은 당신이보아야 할 유일한 것이 아닙니다. 당신이 그것을 사용할 수있는 더 많은 방법이 있습니다.워드 프로세서에서

: 자바 프로그래밍 언어에서

자바에서 인터페이스, 인터페이스는 상수, 메소드 서명, 기본 방법을 포함 할 수있는 클래스와 비슷 참조 형은, 정적 메서드 및 중첩 형식 메서드 본문은 기본 메서드 및 정적 메서드에만 있습니다. 인터페이스는 인스턴스화 될 수 없으며 클래스에 의해서만 구현되거나 다른 인터페이스에 의해 확장 될 수 있습니다.

here

가 당신에게 Interface

관련 문제