java日常学习:构造函数练习

#java代码块


##练习一:
/*
需求1 : 统计一个类创建对象的个数。 静态成员变量的应用场景之一。
*/
//创建一个动物类;
class Animal{
String name;
int id;
static int count; //定义一个计数器 非静态成员变量;
//构造代码块;
{
count++;
}
//构造函数;
public Animal(){

	}
	//构造函数;
	public Animal(String name,int id){
		this.name = name;
		this.id = id;
		System.out.println("这个构造函数被调用!");
	}
}


class demo1 {
	public static void main(String[] args) {
		Animal p1 = new Animal();
		Animal p2 = new Animal("小猫",2);
		Animal p3 = new Animal("小狗",3);
		Animal p4 = new Animal("小猪",4);
		Animal p5 = new Animal("小羊",5);
		System.out.println("对象被调用了"+Animal.count+"次");
	}
}

##练习二:
/*
需求2: 自己实现一个Arrays工具类。
toString(); 返回一个使用数组元素拼装好的字符串。
sort();
*/
//我的数组工具类;
class MyArrays{
//输出数组元素函数;
public static String toString(int[] arr){
String result = “”;
for (int i=0;i<arr.length ;i++ ){
if (i0){
result +="["+arr[i]+",";
}else if (i
arr.length-1){
result +=arr[i]+"]";
}else{
result +=arr[i]+",";
}
}
return result;
}
//直接排序类;
public static void sort(int[] arr){
for (int i=0;i<arr.length-1 ;i++ ){
for (int j=1+i;j<arr.length ; j++){
if (arr[j]>arr[i]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
}

class demo2 
{
	public static void main(String[] args) 
	{
		int[] arr = {12,2,14,11,24,5};
		MyArrays.sort(arr);
		String info = MyArrays.toString(arr);
		System.out.println("数组元素是:"+info);
	}
}

用于平时自己复习回顾,如有错误,欢迎指正

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值