构造函数被private修饰后只能通过静态方法获得实例

没有给构造函数加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修饰后只能通过静态方法获得实例
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值