Java

eclipse / 자바 객체형 배열 처리

bokboks 2023. 3. 23. 05:58

안녕하세요

지난 포스팅에서 자바의 클래스 예제문제들과 메소드 매개변수 처리 이후

이번에는 자바 객체형 배열처리에 대하여 알아보겠습니다.

 

 

eclipse / 자바 메소드 매개변수처리(3) , 필드값 처리

public class A11_ParamField { public static void main(String[] args) { // TODO Auto-generated method stub /* # 메서드 매개변수와 필드값의 처리.. 1. 객체의 메서드의 매개변수를 통해서 필드값을 할당/수정/누적 연산 처

stackbok.tistory.com


package javaexp.a07_multiObj;

public class A01_ObjArray {
	public static void main(String[] args) {
		/*
		 # 객체형 배열 처리..
		 1.하나의 클래스에서 만들어진 객체는 여러개의 배열로 사용할 수 있다.
		 2.객체 배열..
		 	단위객체명[] 배열명 = new 단위객체명[갯수];
		 	단위객체명[] 배열명 = {new 객체명(),new 객체명()...};
		 	배열명[index번호] ; 호출
		 	배열명[index번호] = new 객체명(); 할당
		 */
		Student []arr1 = new Student[3];
		//각 index별로 실제 객체를 할당하고 메서드를 사용
		arr1[0] = new Student(1,"홍길동"); arr1[0].setPoint(80);
		arr1[1] = new Student(1,"신길동"); arr1[1].setPoint(90);
		arr1[2] = new Student(1,"마길동"); arr1[2].setPoint(100);
		int tot =0;
		//해당 메서드를 통해서 점수가 return이 되기 때문에 tot이라는 변수에 누적할수 있다.
		//리턴값이 있으면 해당 메서드를 호출하는곳에서 데이터를 활용이 가능
		arr1[0].showInfo();
		arr1[1].showInfo();
		arr1[2].showInfo();
		
		Fruit []arr2 = new Fruit[3];
		arr2[0] = new Fruit("사과",3000);
		arr2[1] = new Fruit("바나나",4000);
		arr2[2] = new Fruit("딸기",12000);
		for(int idx=0;idx<arr2.length;idx++) {
			arr2[idx].show();
		}
		Fruit []arr3 = {new Fruit("오렌지",1200),new Fruit("키위",1500),
						new Fruit("수박",15000)}; //선언과 동시 할당
		//for each 구문을 통한 처리
		//for(단위객체: 배열)
		for(Fruit fru : arr3) {
			fru.show();
		}
		/*
		 ex2) Computer 클래스 선언 : cpu,ram,hdd 속성을 선언하고
		 객체선언과 할당을 동시
		 	생성자 : 필드 초기화 , 메서드 필드 출력
		 	
		 */
		Computer []arr4 = {new Computer("3.2Ghz i7",16,256),
						   new Computer("3.1Ghz i5",8,256),
						   new Computer("3.4Ghz i9",32,500)};
		
		// arr4[0] == new Computer("3.2Ghz i7",16,256)
		for(Computer com :arr4) {
			com.comInfo();
		}
	}
}
class Computer{
	String cpu;
	int ram,hdd;
	Computer(String cpu,int ram,int hdd){
		this.cpu = cpu;
		this.ram = ram;
		this.hdd = hdd;
	}
	void comInfo() {
		System.out.println(cpu+"\t");
		System.out.println(ram+"\t");
		System.out.println(hdd+"\t");
	}
}
class Fruit{
	//ex) Fruit 필드 : 과일종류 , 가격 ,
		//			생성자 : 필드값 초기
		//			메서드 show(): 종류와 가격 출력.
		// 배열로 3개를 선언 및 할당, show() 호출..
	String kind;
	int price;
	Fruit(String kind, int price){
		this.kind = kind;
		this.price = price;	
	}
	void show() {
		System.out.println(kind+"\t"+price);
	}
}
class Student{
	int no;
	String name;
	int kor;
	Student(int no,String name){
		this.no = no;
		this.name = name;
	}
	void setPoint(int kor) {
		this.kor = kor;
	}
	void showInfo() {
		System.out.println(no+"\t"+name+"\t"+kor);
	}
}

이상으로 자바 객체형 배열처리에 대하여 알아보았습니다

감사합니다.