archive
9장 인터페이스, 람다식, 패키지 연습 문제 및 LAB 문제 본문
1. 자율주행 자동차 추상메소드 실습 예제
package 자율주행자동차;
public interface OperateCar {
void start();
void stop();
void setSpeed(int speed);
void turn(int degree);
}
package 자율주행자동차;
public class AutoCar_자동차제조사구현부분 implements OperateCar {
public void start() {
System.out.println("자동차가 출발합니다.");
}
public void stop() {
System.out.println("자동차가 정지합니다.");
}
public void setSpeed(int speed) {
System.out.println("자동차가 속도를 "+speed+"km/h로 바꿉니다.");
}
public void turn(int degree) {
System.out.println("자동차가 방향을 "+degree+"도 만큼 바꿉니다.");
}
}
package 자율주행자동차;
public class AutoCarTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
AutoCar_자동차제조사구현부분 car=new AutoCar_자동차제조사구현부분();
car.start();
car.setSpeed(30);
car.turn(15);
car.stop();
}
}
2. 객체 비교하기 Comparable 실습 예제
package 객체비교;
public class Rectangle implements Comparable {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width=width;
this.height=height;
}
public int getArea() {
return width*height;
}
public String toString() {
return "Rectangle [width="+width+", height="+height+"]";
}
//중요, 오버라이드해서 원하는 값 출력하도록 인터페이스 구체화
public int compareTo(Object other) {
Rectangle otherRect=(Rectangle) other; // 여기 뭐 하는 거지 아 다른 애 객체 생성...? 아 형변환
if(this.getArea()<otherRect.getArea())
return -1;
else if(this.getArea()==otherRect.getArea())
return 0;
else
return 1;
}
}
package 객체비교;
public class RectangleTest {
public static void main(String[] args) {
Rectangle rec1=new Rectangle(100,30);
Rectangle rec2=new Rectangle(200,10);
int result=rec1.compareTo(rec2);
if (result==1) {
System.out.println(rec1+"가 더 큽니다.");
}
else if (result==-1) {
System.out.println(rec2+"가 더 큽니다.");
}
else {
System.out.println("같습니다");
}
}
}
'Java > 스터디 예제 풀이' 카테고리의 다른 글
15장 제네릭과 컬렉션 연습 문제 및 LAB 문제-2 (0) | 2023.03.03 |
---|---|
15장 제네릭과 컬렉션 연습 문제 및 LAB 문제-1 (0) | 2023.03.03 |
7장 상속 연습 문제 및 LAB 문제 -2 (0) | 2023.03.03 |
7장 상속 연습 문제 및 LAB 문제 -1 (0) | 2023.03.03 |
6장 클래스와 메소드 심층 탐구 연습 문제 및 LAB 문제 (0) | 2023.02.05 |