Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

WON.dev

chapter02 : Object_equals 본문

JAVA/chapter20_api

chapter02 : Object_equals

GAWON 2023. 5. 30. 18:17
package org.joonzis.ex;
class Computer{
	private String model;
	private int price;
	public Computer(String model, int price) {
		this.model = model;
		this.price = price;
	}
	@Override
	public String toString() {
		return "모델 : " + model + ", 가격 : " + price;
	}
	@Override
	public boolean equals(Object obj) {
		if(obj != null && obj instanceof Computer) {
			Computer another = (Computer)obj;
			return model.equals(another.model) && price == another.price;
		}else {
			return false;
		}
	}
}
public class Ex02_Object_equals {
	public static void main(String[] args) {
		
		Computer myCom1 = new Computer("레노버 요가", 100);
		Computer myCom2 = new Computer("레노버 요가", 100);
		
		// 1. == : 참조 비교 (주소 비교)
		if(myCom1 == myCom2) {
			System.out.println("같은 종류의 컴퓨터");
		}else {
			System.out.println("다른 종류의 컴퓨터");
		}
		
		
		// 2. equals()
		//	1) Object의 equals 메소드 : 객체 비교 불가
		//	2) Computer 클래스에서 equals 메소드 오버라이드
		if(myCom1.equals(myCom2)) {
			System.out.println("같은 종류의 컴퓨터");
		}else {
			System.out.println("다른 종류의 컴퓨터");
		}
		
	}
}

'JAVA > chapter20_api' 카테고리의 다른 글

chapter06 : StringBuffer  (0) 2023.05.30
chapter05 : String  (0) 2023.05.30
chapter04 : System  (0) 2023.05.30
chapter03 : Object_clone  (0) 2023.05.30
chapter01 : Object  (0) 2023.05.30