// 2. I want to hide this method. It should only be callable from superclass Shape
구현을 잠 그려면 Shape 메서드 final
을 만들 수 있습니다. 심지어 하위 클래스 유형 (예 : Triangle
)을 반환하는 오버로드 된 메서드는 컴파일러에 의해 플래그가 지정됩니다.
public static final Shape createShapeFromXML(String xml) { ... }
편집 :
:
public class Shape {
public static final Shape createShapeFromXML(String xml) {
if (xml.equals("Triangle")) {//removed parse for demo compliation
return Triangle.createShapeFromXML(xml);
} else {
return new Shape();
}
}
}
public class Triangle extends Shape{
public static Triangle createShapeFromXML(String xml) {
return new Triangle();
}
}
위의 컴파일러 오류가 발생합니다 컴파일하려고 : 증거
코멘트에 대화에 응답
, 나는 다음과 같은 제공
mybox:src akf$ javac Triangle.java
Triangle.java:3: createShapeFromXML(java.lang.String) in Triangle cannot override createShapeFromXML(java.lang.String) in Shape; overridden method is static final
public static Triangle createShapeFromXML(String xml) {
^
1 error
이것은 JLS을 참조하여 설명 할 수 있습니다. 두 부분 (분류 방법에 의해) 8.4.6.2 숨지
:
If a class declares a static method, then the declaration of that method is said to hide any and all methods with the same signature in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class.
하고 8.4.3.3 final
방법에서 :
A method can be declared final to prevent subclasses from overriding or hiding it. It is a compile-time error to attempt to override or hide a final method.
함께 두 퍼팅 정적 메서드의 서명에 final
을 추가하면 해당 메서드가 하위 클래스에 의해 숨겨지지 않도록 보호됩니다.컴파일시 검사를 시행합니다.
출처
2010-12-01 03:52:33
akf
특히 이것은 추상적 인 공장의 예라고 생각합니다. 나는 GoF가 그들을 두 개의 분리 된 패턴으로 분류 한 이유를 정말로 모른다. –
공장 패턴에 +1. 그것은 형태 클래스 책임 fopr 객체 생성 –
@ Karl : FactoryMethod와 AbstractFactory의 기본적인 차이점은 FactoryMethod가 클래스 계층 구조 (추상 기본 클래스) 내부에서 호출되는 반면 AbstractFactory는 외부에서 사용된다는 점입니다. (GoFBook은 FactoryMethod가 "클래스 기반"이지만 AbstractFactory는 "객체 기반"이라는 말로이 사실을 암시합니다.) - JavaRanch FAQ에서. –