If you make your constructor "private" you can't invoke the constructor from another class... But you can still invoke it from the SAME class. In Netbeans we are used that Netbeans will generate automatically a Main class and a pvsm (public static void main[] args) method in the main class. In this case if you try to instantiate a class using a private constructor you cant... You have to give another ways (have a look to singletons). But if you put a pvsm in the class were the private constructor is defined, no problem you can instantiate the class.
package pkg3.pkg31;
class Class1 {
protected int a;
protected int b;
private Class1(int a, int b) {
this.a = a;
this.b = b;
}
protected int calculation() {
return a + b;
}
public static void main(String[] args) {
System.out.println(new Class1(1, 2).calculation());
}
}
run:
3
BUILD SUCCESSFUL (total time: 0 seconds)
No comments:
Post a Comment