본문 바로가기

아옳옳의 코딩공부/아옳옳 자바코딩공부

2021-04-05 자바공부 (Object 클래스 )

반응형

모든 클래스들의 최상위 클래스 

자바의 모든 클래스들은 내가 모르는 사이에 Object 클래스를 상속받고 있다 !! 

트리 구조  , 계층 구조  : 하나의 뿌리에서 여러개의 가지를 치는 형상 

Object 클래스

위와처럼 많은 메소드들을 담고 있는데 아까말했다 시피 모든 클래스는 Object 클래스를 상속 받기 때문에 다른 클래스에서도 사용할 수 있는것이다. 

 

자주 사용하는 것 몇가지 먼저 해보도록 하자 

toString 메소드 , getClass메소드

 

package clone;

public class GetClass_toString {
	int x,y;
	

	public GetClass_toString(int x, int y) {
		
		this.x = x;
		this.y = y;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "point(" + x + "," + y + ")" ;
	}

	public static void main(String[] args) {
		//getClass 사용
		GetClass_toString a = new GetClass_toString(2,3);
		System.out.println(a.getClass().getName());
		//toString 사용 
		GetClass_toString b = new GetClass_toString(2,3);
		System.out.println(b.toString());

	}

}

출력결과

 

equals 메소드

== 연산자는 참조 값을 비교를 한다. 따라서 인스턴스간 내용을 비교하려면 내용비교 기능의 메소드가 필요하다 

아래 코드를 보면 equals 메소드를 다시 재정의 해서 사용한 부분이 있으니 참고 하면 될거 같다  

package equals_ex;

class Rect {
	int width;
	int heith;

	public Rect(int width, int heith) {
		this.width = width;
		this.heith = heith;
	}

	@Override
	public boolean equals(Object obj) {

		if (obj instanceof Rect) {
			Rect re = (Rect) obj;
			if (width * heith == re.width * re.heith)
				return true;
			else
				return false;

		}
		return false;
	}

}

public class Equals_ex {

	public static void main(String[] args) {
		Rect rect1 = new Rect(2, 3);
		Rect rect2 = new Rect(3, 2);
		Rect rect3 = new Rect(1, 2);

		if (rect1.equals(rect2)) {
			System.out.println("같음");
		}else {
			System.out.println("다름");
		}
		if (rect2.equals(rect3)) {
			System.out.println("같음");
		}else {
			System.out.println("다름");
		}
		if (rect1.equals(rect3)) {
			System.out.println("같음");
		}else {
			System.out.println("다름");
		}

	}
}

 

clone 메소드 

 복제를 하는 것이라고 생각하면 된다 복제의 종류는 2가지 있는데 

얕은 복사와 깊은 복사가 있다. 

그림을 보면 이해가 쉬울 것이다. 

위 그림을 보면 각각의 인스턴스 전부를 복사할것인지 하나의 인스턴스만 복사 할 것인지에 따라 달라진다. 

코드를 보면 어떤 의미인지 바로 이해가 될것 이다. 

 

////////////////////////// 메인 ///////////////////////
public class DeepCopy {

	public static void main(String[] args) {
		//인스턴스 생성
		PersonnalInfo naruto = new PersonnalInfo("나루토", 24, "나뭇잎마을", "호카케업무");
		//복사를 할곳 
		PersonnalInfo gai;
		

		try {
			//인스턴스 복사 
			gai = (PersonnalInfo) naruto.clone();
			//인스턴스 정보수정 
			naruto.change("카카시", 50, "모래마을", "선생님");
			naruto.showPersonnalInfo();
			gai.showPersonnalInfo();
		}
		catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
	}
}
////////////////////////// 비즈니스 ///////////////////////


public class Business implements Cloneable {
	private String company;
	private String work;
	
	public Business(String company, String work) {
		this.company = company;
		this.work = work;
	}
	
	public void showBusinessInfo() { 
		System.out.println("회사 :" +  company );
		System.out.println("업무 :" +  work );
	}

	public void change( String company , String work) {
		this.company = company;
		this.work = work;
	}
	
	@Override 
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
	
}
/////////////////////////////////퍼스날인포////////////////////
public class PersonnalInfo implements Cloneable{

	private String name;
	private int age;
	private Business bz;
	//생성자 
	public PersonnalInfo(String name, int age,  String company , String work) {
		super();
		this.name = name;
		this.age = age;
		bz = new Business(company , work );
	}
	
	//정보출력 메소드 
	public void showPersonnalInfo() {
		System.out.println("이름 :" + name);
		System.out.println("나이 :" + age);
		bz.showBusinessInfo();
	}
	//정보 수정 메소드
	public void change(String name, int age,  String company , String work) {
		this.name = name;
		this.age = age;
		bz.change(company,work);
		
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		//Object 클래스의 clone 메소드 호출 결과를 얻음 
		PersonnalInfo copy = (PersonnalInfo)super.clone();
		//깊은 복사의 형태로 복사본 수정 
		copy.bz = (Business) bz.clone();	
		//완성된 복사본의 참조를 반환 
		return copy;
	}
	
	
}

보이는것처럼 처음에 복사를 한후에 기존 이스턴스의 정보를 변경한뒤에 출력해주었을때 지금처럼 복사도 잘 되었고 변경도 잘 된것을 확인 할수 있다. 

 

반응형