面向对象案例

/**
 *利用面向对象实现
 *定义一个数组,求数组最大值,最小值,和,平均数
 */
public class ArrayOpp {
	public static void main(String[] args) {
		int[] data = new int[]{1,5,6,4,2,3,7};        //创建数组对象
		
		Array ns = new Array(data);                   //创建自定义对象,并完成相关数据计算
		System.out.println("sum是"+ ns.getSum());
		System.out.println("Avg是"+ ns.getAvg());
		System.out.println("Min是"+ ns.getMin());
		System.out.println("Max是"+ ns.getMax());
	}
}
/*
数组的面向对象创建过程
*/
class Array{
	private int sum = 0;//添加初始值
	private double avg = 0.0;
	private int max =0;
	private int min = 0;
	
	public Array() {}//无参构造  
	
	public Array(int[] arr) {//有参构造,注意此处写法,只有public Array
                
                //数组比较大小可用此种方式,将数组第1项分别赋值为最大值和最小值,再与后面数值进行比较
		for (int i = 0;i < arr.length;i++) {
			
			this.max = arr[0];
			this.min = arr[0];
			
			if (arr[i] > this.max) {
				this.max = arr[i];
			}
			if (arr[i] < this.min) {
				this.min = arr[i];
			}
			
			this.sum += arr[i];
			
		}
		this.avg += this.sum / arr.length;
	}
       
	public int getSum() {
		return this.sum;
	}

	public double getAvg() {
		return this.avg;
	}

	public int getMax() {
		return this.max;
	}

	public int getMin() {
		return this.min;
	}
	
}