자바의 객체 생성 방법(3가지) 

1. new 연산자 이용

Person p = new Person();

2. 메소드의 매개변수를 전달하여 객체를 얻어오는 방법 ( CallByReference) 

3. 메소드의 반환형을 통해서 객체를 얻어오는 방법

 

2. 메소드의 매개변수를 전달하는 방법(2가지) 

1) CallByValue 

값에 의한 전달방법, 기본자료형 8가지를 전달한다

원본의 값을 복사하여 전달 -> 복사한 값을 계산 -> 원본은 변경되지 않는다

//Caller Method---매개변수----> Worker Method
//CallByValue
public class CallByValue {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int r=-1,g=-1,b=-1;//css(rgb(0~255)숫자로 표현)
		System.out.println("before: red="+r+"green="+g+"blue"+b);
		//색깔 변경 
		change_color(r,g,b);
		System.out.println("after: red="+r+"green="+g+"blue"+b);
	}

	static void change_color(int r, int g, int b) {
		r+=10;
		g+=50;
		b+=100;
		System.out.println("메소드내부:red="+r+"green="+g+"blue"+b);
	}
}/*
before: red=-1green=-1blue-1
메소드내부:red=9green=49blue99
after: red=-1green=-1blue-1
*/

 

2) CallByReference 

주소에 의한 전달방법, 객체(=주소값)를 전달한다

원본이 전달 -> 원본이 변경된다

( 좀 더 구체적으로 설명하자면 여기서 color 객체가 매개변수로 전달되면서 새로운 RGBColor 객체가 생성된다.

이 rgbcolor 객체는 change_color 메소드 범위 내에 존재하고, 기존 color 객체의 주소를 공유한다. )

//색깔을 변경시켜주는 새로운 자료형
class RGBColor{
	int r,g,b;
	
	RGBColor(int r, int g, int b){
		this.r=r;
		this.g=g;
		this.b=b;
	}	
}
public class CallByRef {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		RGBColor color = new RGBColor(-1,-1,-1);//css(rgb(0~255)숫자로 표현)
		System.out.println("before: red="+color.r+"green="+color.g+"blue"+color.b);
		//색깔 변경 
		change_color(color);
		System.out.println("after: red="+color.r+"green="+color.g+"blue"+color.b);
	}
	
	static void change_color(RGBColor rgbcolor) {
		rgbcolor.r+=10;
		rgbcolor.g+=50;
		rgbcolor.b+=100;
		System.out.println("메소드내부: red="+rgbcolor.r+"green="+rgbcolor.g+"blue"+rgbcolor.b);
	}
}
/*
before: red=-1green=-1blue-1
메소드내부: red=9green=49blue99
after: red=9green=49blue99
*/

 

 

3. 메소드의 반환형을 통해서 객체를 얻어오는 방법

API문서(shift + f2) 

-> 클래스 생성자를 통해 객체생성방법을 알 수 있다

예) API문서에서 Runtime 클래스를 살펴보면 이 클래스는 생성자가 존재하지 않는다.

따라서 기본생성자로 객체를 생성하는 방법인  Runtime rt = new Runtime();  를 이용하면 에러가 발생한다.

Runtime 클래스의 생성자가 은닉화되어 있기 때문이다.  Runtime 객체를 반환하는 getRuntime() 메소드를 통해

객체를 생성할 수 있다.

 

=> 여기서 Runtime 클래스는 싱글톤 패턴(하나의 클래스에서 하나의 인스턴스만 만들 수 있도록 함)으로, 

클래스 내부에서

class AAA{

    private static AAA a = new AAA();

//자기자신 인스턴스 생성

 

private AAA(){...} 

//생성자(외부에서 접근x)

 

public static AAA geta(){

    return a;

}

//생성한 인스턴스를 반환

이런 과정을 거쳐 하나의 인스턴스만으로 재사용을 한다

* 싱글톤 패턴은 나중에 더 자세히 포스팅 할 예정

 

//메소드의 반환형을 통해서 객체를 얻어오는 방법
public class GCCollector {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Runtime r=Runtime.getRuntime();
		System.out.println("r=> "+r);
		System.out.println(r.totalMemory());
		System.out.println(r.freeMemory());
	}
}
/*
r=> java.lang.Runtime@15db9742
255328256
252664840
*/

현재 시간 출력하기

Date 클래스 자체적으로 정의해둔 toString() 메소드로 인해 출력결과가 아래와 같이 나온다

package j210114;
//오늘 날짜 출력하기-> Date, Calendar
import java.util.Date;
public class SimpleTest {
//main은 최대한 짧게!
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		SimpleTest st = new SimpleTest();
		Date d = st.getDate();
		st.setDate(d);
	}
	
	Date getDate() {
		Date d = new Date();
		return d;
	}

	void setDate(Date d) {
		System.out.println("d=>"+d);
		//System.out.println("오늘날짜(d): "+d.toString());
	}
}
/*
d=>Mon Jan 18 22:01:24 KST 2021
오늘날짜(d): Mon Jan 18 22:01:24 KST 2021
*/

자바프로그램 메모리 사용량 확인하기

자바의 특징 중 하나인 GC collector

불필요하는 메모리가 발생하면 자동으로 메모리 관리를 해준다

public class GCCollector {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Runtime r=Runtime.getRuntime();

		//1024개 데이터를 저장할 공간생성
		byte test[]=new byte[1024];
		test[1]=20; test[2]=34;//,,,,
		System.out.println("test=>"+test);
		System.out.println("before 사용메모리양=>"+(r.totalMemory()-r.freeMemory())/1024+"K");
		
		test=null;//저장된 위치를 알수없게 된다->메모리 제거는 아님
		System.gc();//수동으로 쓸데없는 메모리를 제거시켜주는 메소드
		System.out.println("after 사용메모리양=>"
				+(r.totalMemory()-r.freeMemory())/1024+"K");
	}
}
/*
test=>[B@6d06d69c
before 사용메모리양=>2600K
after 사용메모리양=>1845K
*/

 

+ Recent posts