2013-05-11 3 views
5

최근에 저는 XML 파서로 작업 해 왔습니다. 이것은 이제 막 시작되었으며 Java에서 DOM 파서 클래스를 사용하는 방법을 이해했습니다. 즉 DocumentBuilderFactoryDocumentBuilder은 XML 문서를 구문 분석합니다.추상 클래스 "DocumentBuilderFactory"가 새 인스턴스를 인스턴스화 할 수있게되었습니다.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder();    

나 자신은 DocumentBuilderFactoryDocumentBuilder로, 새로운 인스턴스를 인스턴스화하는 데 사용할 수 있습니다, 어떻게 추상 클래스를 제공한다 해달라고 부탁 무엇? 그리고 또 다른 예에서 나는 참조 :

Calendar calendar = Calendar.getInstance(); 
System.out.println(calendar.get(Calendar.DATE)); 
  1. 는 지금까지 내가 아는 한, 당신은 추상적이고 인터페이스 클래스 (즉 객체를 생성) 인스턴스화 할 수 없습니다. 나 맞아?
  2. getInstance()newInstancce() 메소드는 위의 추상 클래스의 인스턴스를 생성합니까?

나는 추상 클래스와 그 새로운 객체를 사용하는 것에 대해 빠뜨린 것이 있습니까?

답변

9

그 방법은 이며 하위 클래스DocumentBuilder으로 반환하며 이는 구체적인 구현입니다.

개체의 정확한 클래스는 중요하지 않으며 단지 DocumentBuilder임을 알아야합니다. 이 메소드는 런타임에 결정된 인스턴스를 반환하거나 적합하다고 판단되는 인스턴스를 반환 할 수 있습니다. 방법 newInstance()Class의 같은 이름의 방법과 혼동되지 않음을

System.out.println(dbf.getClass()); 

참고 : 당신이 알고 궁금 경우

, 당신은 실제이 같은 클래스를 인쇄 할 수 있습니다 즉,이 두 가지가 다릅니다.

// a static method of this class 
DocumentBuilderFactory.newInstance(); 

// an instance method of Class 
DocumentBuilderFactory.class.newInstance(); 

혼동을 야기한 불행한 선택입니다. DocumentBuilderFactory의 실제 인스턴스가 itself.It 내가 감히 무엇처럼되지 않습니다하지 DocumentBuilderFactory의 하위 유형을 반환하는 정적 추상 팩토리 메소드입니다

+0

내가이를 내 질문에 약간의 추가 . – MKod

+0

@Bohemian 그냥 골동품. DocumentBuilderFactory 클래스는 newDocumentBuilder와 같은 메소드를 노출하여 다른 객체 인스턴스를 반환하므로 확실히 AbstractFactory로 볼 수 있습니다. 그러나 DocumentBuilderFactory.newInstance()는 다소 정적 팩토리 메소드 –

+0

입니다. 소스 코드를 보았습니다. 도와 주셔서 감사합니다. – MKod

3

, 당신은 이해 :

DocumentBuilderFactory dbf = new DocumentBuilderFactory(); 

DocumentBuilderFactory#newInstance(), DocumentBuilderFactory의 새로운 인스턴스를 취득합니다. 이 정적 메서드는 새 팩토리 인스턴스를 만듭니다. 이 메소드는 다음 순서의 조회 프로 시저를 사용하여로드 할 DocumentBuilderFactory 구현 클래스를 판별합니다.

newInstance() 추상적하지 않고 DocumentBuilderFactory 참조 변수에 해당 객체에 대한 참조를 할당합니다 DocumentBuilderFactory의 구현 클래스 (하위 유형)의 인스턴스를 반환합니다.

+0

정확히 전 가정합니다 : DocumentBuilderFactory dbf = new DocumentBuilderFactory(); . "하위 유형을 반환합니다"라고 말하면 하위 유형 클래스를 알고 싶습니다. 미안해. 거의 다 왔어.하지만 내 생각에는 미묘한 차이가있다. – MKod

+0

아니, 소스 코드를 살펴보십시오! – NINCOMPOOP

+0

나는 그것을 얻었고, 나는 근원을 들여다 보았다. 도와 주셔서 감사합니다. – MKod

1

정적 방법입니다. 인스턴스에 대한 참조없이 클래스의 정적 메서드 (또는 해당 클래스의 모든 클래스)를 호출 할 수 있습니다.

+0

very true.thanks Dev – MKod

1

아래의 코드를 시도한 후 모두에게 감사드립니다.

캘린더 cls = Calendar.getInstance();
날짜 dt = new Date();
System.out.println (cls.getClass()); // < ------ 1
DocumentBuilderFactory dbls = DocumentBuilderFactory.newInstance(); System.out.println (dbls.getClass()); // < ------ 2
DocumentBuilder db = dbls.newDocumentBuilder();
System.out.println (db.getClass()); "DocumentBuilderFactoryImpl라는

********Output****** 
    class java.util.GregorianCalendar 
    class com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl 
    class com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl 

가) 정적 메소드"DocumentBuilderFactory.newInstance() "반환 하위 클래스 인스턴스 : // < -------- 3

는 그리고 나는 때라도 출력을 볼 수 ".

B)는 "DocumentBuilderFactoryImpl는"추상적 "DocumentBuilderFacotory"클래스의 하위 클래스, 따라서 I 줄 경우에는 문제가 없다 :

DocumentBuilderFacotryImpl의 dbls DocumentBuilderFactory.newInstance =();
// ----- DocumentBuilderFactory를주는 대신 dbls = DocumentBuilderFactory.newInstance();

및 DocumentBuilderImpl db = dbls.newDocumentBuilder()에도 동일하게 적용됩니다.
// ---- DocumentBuilder 대신 db = dbls.bewDocumentBuilder();

결론 : newInstance(), newDocumentBuilder(), getInstance()는 하위 클래스 객체를 반환합니다. abstract 클래스는 새로운 Object를 생성 할 수 없지만, abstract 클래스 (즉, 부모) 참조 변수에 subclass 객체를 할당 할 수 있습니다. 예 :

추상 클래스 A는 { }
클래스 B는 확장하는 { }

우리는 말할 수있다 :

A a = new B(); 

하지만

A a = new A(); 
+0

예, 당신이 알아 낸 것 같아요. – Bohemian

+0

+1, 그것을 알아 내기위한 !!!! – NINCOMPOOP

관련 문제