// 2. I want to hide this method. It should only be callable from superclass 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を参照して説明することができます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
方法から:
(クラスメソッドによって)8.4.6.2非表示から
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.
一緒に2を入れて、静的メソッドのシグネチャにfinal
を追加すると、そのメソッドがサブクラスによって隠されないように保護されます。コンパイル時のチェックが強制されます。
出典
2010-12-01 03:52:33
akf
具体的には、これは抽象ファクトリの例とみなされます。私はGoFが2つの別々のパターンとしてそれらを分類した理由を本当に知りません。 –
工場パターンに+1します。それはシェイプクラスの責任foprオブジェクトの作成 –
@カール:FactoryMethodとAbstractFactoryの基本的な違いは、FactoryMethodがクラス階層(抽象基底クラス)から呼び出され、AbstractFactoryは外部から使用されるということです。 (GoFBookは、FactoryMethodが "クラスベース"であるのに対し、AbstractFactoryは "オブジェクトベース"であると言って、この事実を暗示しようとしています) - JavaRanch FAQから。 –