정렬하는 기능을 추가하였다.

	private void handleSort() {
		for(int i =n-1;i>0;i--) {
			for(int j=0;j<i;j++) {
				if(Shapes[j].computearea() > Shapes[j+1].computearea()) {
					Shape tmp = Shapes[j];
					Shapes[j] = Shapes[j+1];
					Shapes[j+1] = tmp;
					
				}
			}
		}
		
	}

 

같은 알고리즘을 데이터의 타입이 다르다는 이유로 반복적으로 타이핑하는것은 불만스럽다는

생각을 하게되었다.

 

그런것을 generic하지 않다라고 말을한다.

그 의미는 Shape타입 데이터만 가능한 메서드이다.

 

어떠한 데이터가 들어오든 가능하게 하는것을 

generic하다 라고 말을한다.

 

package chapter5;

public interface MyComparable {
	public int compareTo(Object o);
}

MyComparable 인터페이스 생성!

 

package chapter5;

public abstract class Shape implements MyComparable{
	public  String shapeName;
	
	public Shape(String name) {
		shapeName =name;
	}
	
	public abstract double computearea();
	public abstract double computePerimeter();
	
	public int compareTo(Object o) {
		double myArea = computearea();
		double yourArea = ((Shape)o).computearea();
		if(myArea < yourArea)
			return -1;
		else if(myArea == yourArea)
			return 0;
		else
			return 1;
	}

}

compareTo 메서드 구현

 

	private void handleSort(MyComparable[] data, int size) {
		for(int i =size-1; i>0; i--) {
			for(int j=0; j<i; j++) {
				if(Shapes[j].compareTo(Shapes[j+1])>0) {
					MyComparable tmp = data[j];
					data[j] =data[j+1];
					data[j+1] = tmp;
				}
			}
		}
	}

정렬 알고리즘을 Gereric하게 바꾸어보았다!

이제는 모든 타입의 데이터를 (MyComparable 인터페이스를 implements하고 메서드를 구현하기만 한다면)

사용 가능하다.

 

자바 API가 제공해주는 Arrays.sort 를 쓰기만 하면 sort를 구현할 필요도 없다.

Comparable 인터페이스 또한 원래 있는 인터페이스이다.

 

Interface vs abstract class

 

추상 메서드로만 구성된 추상 클래스는 인터페이스와 완전히 동일한가?

 

다중 상속

자바에서는 다중 상속을 허용하지 않는다.

하지만 하나의 클래스가 여러개의 Interface를 implement하는 것은 가능

 

+ Recent posts