没有给构造函数加private时,可以new对象来访问,同时我们并没有写构造方法,因为它会自己去创建
class ArrayTool{
public static void printArray(int[] arr){
//打印数组
System.out.print("[ ");
for(int x = 0;x < arr.length;x++){
if(x == arr.length-1){
System.out.println(arr[x]+" ]");
}else {
System.out.print(arr[x]+" , ");
}
}
}
}
测试类
class Test{
public static void main(String[] args){
int[] arr = {11,22,33,44,55,34};
ArrayTool at = new ArrayTool() ;
at.printArray(arr) ;
}
}
上面这个是通过无参构造方法创建的对象,如何将对象的创建(无参构造方法)禁止调用? private关键字
class ArrayTool{
private ArrayTool(){}
public static void printArray(int[] arr){
//打印数组
System.out.print("[ ");
for(int x = 0;x < arr.length;x++){
if(x == arr.length-1){
System.out.println(arr[x]+" ]");
}else {
System.out.print(arr[x]+" , ");
}
}
}
}
class Test{
public static void main(String[] args){
int[] arr = {11,22,33,44,55,34};
ArrayTool at = new ArrayTool() ;
at.printArray(arr) ;
}
}
我们编译说ArrayTool()可以在ArrayTool()中访问private,所以对象的创建(无参构造方法)禁止调用
没有其它构造函数就只能通过静态方法来获得
class ArrayTool{
private ArrayTool(){}
public static void printArray(int[] arr){
System.out.print("[ ");
for(int x = 0;x < arr.length;x++){
if(x == arr.length-1){
System.out.println(arr[x]+" ]");
}else {
System.out.print(arr[x]+" , ");
}
}
}
}
class Test{
public static void main(String[] args){
int[] arr = {11,22,33,44,55,34};
//ArrayTool at = new ArrayTool() ;
//at.printArray(arr) ;
//类名.成员方法() ;
ArrayTool.printArray(arr);
}
}
成功输出
当构造函数被private修饰后只能通过静态方法获得实例