Object클래스
: 모든 클래스의 최고 조상
- equals(Object obj)
: 매개변수로 객체의 참조변수를 받아서 주소값을 비교하여 결과를 boolean값으로 알려 주는 역할
★ equals 메서드로 주소값이 아닌 value 값 비교하기 → equals메서드 오버라이딩하기
class person {
long id;
public boolean equals(Object obj) {
if(obj!=null && obj instanceof Person) {
return id == ((Person)obj).id;
} else {
return false;
}
}
Person(long id) {
this.id=id;
}
}
class EqualsEx2 {
public static void main(String[] args) {
person p1 = new Person(8011081111222L);
person p2 = new Person(8011081111222L);
if(p1==p2)
System.out.println("p1=p2");
else
System.out.println("p1!=p2");
if(p1.equals(p2))
System.out.println("p1=p2");
else
System.out.println("p1!=p2");
}
}
- hashCode()
: hashing기법에 사용되는 해시함수를 구현한 것.
: 일반적으로 해시코드가 같은 두 객체가 존재하는 것이 가능,
하지만 Object클래스에 정의된 hashCode메서드는 객체의 주소값을 이용해서 해시코드를 만들어 반환하기 때문
에 서로 다른 두 객체는 결코 같은 해시코드를 가질 수 없음
★ hashCode 메서드로 주소값이 아닌 value 값 비교하기 →. hashCode 메서드 오버라이딩하기
- toString()
: 인스턴스에 대한 정보를 문자열로 제공할 목적으로 정의한 것.
- clone()
: 자신을 복제하여 새로운 인스턴스를 생성하는 일을 함.
※ 단순히 인스턴스변수 값만을 복사 → 참조변수 타입의 인스턴스 변수가 정의되어 있는 클래스는 완전히 인스턴스 복제가 이뤄
지지 않음.
class Point implements Cloneable {
int x;
int y;
Point(int x, int y) {
this.x=x;
this.y=y;
}
public String toString() {
return "x="+x +", y="+y;
}
public Object clone() {
Object obj = null;
try {
obj = super.clone();
} catch(CloneNotSupportedException e) {}
return obj;
}
}
class CloneEx1 {
public static void main(String[] args) {
Point original = new Point(3,5);
Point copy = (Point)original.clone();
System.out.println(original);
System.out.println(copy);
}
}
● Cloneable인터페이스를 구현한 클래스의 인스턴스만 clone()을 통한 복제가 가능한데, 그 이유는 인스턴스의 데이터 보호를 위해서
- 공변(함께 변하는) 반환타입
: 오버라이딩할 때 조상 메서드의 반환타입을 자손 클래스의 타입으로 변경을 허용하는 것.
int[] arr = {1,2,3,4,5};
int[] arrClone = arr.clone();
//same
int[] arr = {1,2,3,4,5};
int[] arrClone = new int[arr.length];
System.arraycopy(arr,0,arrClone,0,arr.length);
ArrayList list = new ArrayList();
...
ArrayList list2 = (ArrayList)list.clone();
- 얕은 복사와 깊은 복사
얕은 복사 | - 원본과 복제본이 같은 객체를 공유함 - 원본을 변경하면 복사본도 영향을 받음. |
깊은 복사 | - 원본이 참조하고 있는 객체까지 복제하는 것 - 원본의 변경이 복사본에 영향을 미치지 않음. |
// 얕은 복사
Circle c1 = new Circle(new Point(1,1),2.0);
Cirecle c2 = c1.clone();
import java.util.*;
class Circle implements Cloneable {
Point p;
double r;
Circle(Point p, double r) {
this.p=p;
this.r=r;
}
public Circle shallowCopy() {
Object obj = null;
try {
obj=super.clone();
} catch (CloneNotSupportedException e) {}
return (Circle) obj;
}
public Circle deepCopy() {
Object obj = null;
try {
obj = super.clone();
} catch (CloneNotSupportedException e) {}
Circle c = (Circle) obj;
c.p = new Point(this.p.x,this.p.y);
return c;
}
public String toString() {
return "[p="+p+", r="+r+"]";
}
}
class Point {
int x;
int y;
Point(int x,int y){
this.x=x;
this.y=y;
}
public String toString() {
return "("+x+", "+y+")";
}
}
class ShallowDeepCopy {
public static void main(String[] args) {
Circle c1 = new Circle(new Point(1,1),2.0);
Circle c2 = c1.shallowCopy();
Circle c3 = c1.deepCopy();
System.out.println("c1="+c1);
System.out.println("c2="+c2);
System.out.println("c3="+c3);
c1.p.x=9;
c1.p.y=9;
System.out.println("c1="+c1);
System.out.println("c2="+c2);
System.out.println("c3="+c3);
}
}
Circle c1 = new Circle(new Point(1,1), 2.0);
Circle c2 = c1.shallowCopy(); // 얕은 복사
Circle c3 = c1.deepCopy(); // 깊은 복사
- getClass()
: 자신이 속한 클래스의 Class객체를 반환하는 메서드
: Class객체는 이름이 'Class'인 클래스의 객체이다.
※ 클래스당 단 1개만 존재
- Class객체를 얻는 방법
Class cObj = new Card().getClass(); // 생성된 객체로부터 얻는 방법
Class cObj = Card.class; // 클래스 리터럴로부터 얻는 방법
Class cObj = Class.forName("Card"); // 클래스 이름으로부터 얻는 방법
Card c = new.Card(); // new연산자를 이용해서 객체 생성
Card c = Card.class.newInstance(); // Class객체를 이용해서 객체 생성
'Language > java' 카테고리의 다른 글
java.lang 패키지(StringBuffer, StringBuilder 클래스) (0) | 2022.07.14 |
---|---|
Java_Study_ java.lang 패키지(String클래스) (0) | 2022.07.12 |
Java_Study 예외처리 (0) | 2022.07.11 |
Java_Study 객체지향 프로그래밍_내부 클래스 (0) | 2022.07.07 |
Java_Study 객체지향 프로그래밍_인터페이스 (0) | 2022.07.07 |
댓글