में बिल्डर पैटर्न मैंने हाल ही में जोशुआ ब्लोच द्वारा प्रभावी जावा को पढ़ना शुरू कर दिया है। मुझे बिल्डर पैटर्न [पुस्तक में आइटम 2] का विचार वास्तव में दिलचस्प लगता है। मैंने इसे अपने प्रोजेक्ट में लागू करने की कोशिश की लेकिन संकलन त्रुटियां थीं। बाद सार में है कि मैं क्या करने की कोशिश कर रहा था:प्रभावी जावा
कई विशेषताओं के साथ वर्ग और उसके बिल्डर वर्ग:
public class Main {
public static void main(String args[]) {
NutritionalFacts n =
new NutritionalFacts.Builder(10).carbo(23).fat(1).build();
}
}
मैं:
public class NutritionalFacts {
private int sodium;
private int fat;
private int carbo;
public class Builder {
private int sodium;
private int fat;
private int carbo;
public Builder(int s) {
this.sodium = s;
}
public Builder fat(int f) {
this.fat = f;
return this;
}
public Builder carbo(int c) {
this.carbo = c;
return this;
}
public NutritionalFacts build() {
return new NutritionalFacts(this);
}
}
private NutritionalFacts(Builder b) {
this.sodium = b.sodium;
this.fat = b.fat;
this.carbo = b.carbo;
}
}
कक्षा जहां मैं ऊपर वर्ग इस्तेमाल करने की कोशिश निम्नलिखित संकलक त्रुटि प्राप्त कर रहा हूं:
an enclosing instance that contains effectivejava.BuilderPattern.NutritionalFacts.Builder is required NutritionalFacts n = new NutritionalFacts.Builder(10).carbo(23).fat(1).build();
मुझे समझ में नहीं आता कि संदेश का क्या अर्थ है। कृपया समझाएँ। उपरोक्त कोड ब्लोच द्वारा अपनी पुस्तक में सुझाए गए उदाहरण के समान है।
संभव डुप्लिकेट [एक enclosing उदाहरण जिसमें <मेरे संदर्भ> की आवश्यकता है] (http://stackoverflow.com/questions/ 4297857/एक-संलग्न-उदाहरण-जिसमें-मेरा-संदर्भ-आवश्यक है) –