// 구체적인 클래스
public class Point {
public double x;
public double y;
}
// 추상적인 클래스
public interface Point {
double getX();
double getY();
void setCartesian(double x, double y);
double getR();
double getTheta();
void setPolar(double r, double theta);
}
Point 인터페이스는 클래스 메서드가 접근 정책을 강제한다.
Point 클래스는 구현을 노출한다.
변수 사이에 함수라는 계층을 넣는다고 구현이 저절로 감춰지지 않는다.
형식에 치우쳐서 조회 함수와 설정 함수로 변수를 다룬다고 클래스가 되는 것이 아니다.
추상 인터페이스를 제공해 사용자가 구현을 모른 채 자료의 핵심을 조작할 수 있어야 진정한 의미의 클래스다.
구체적인 클래스와 추상적인 클래스 또다른 예시
// 구체적인 클래스
public interface Vehicle {
double getFuelTankCapacityInGallons();
double getGallonsOfGasoline();
}
// 추상적인 클래스
public interface Vehicle {
double getPercentFuelRemaining();
}
절차적인 도형
public class Square {
public Point topLeft;
public double side;
}
public class Rectangle {
public Point topLeft;
public double height;
public double width;
}
public class Circle {
public Point center;
public double radius;
}
public class Geometry {
public final double PI = 3.14159265;
public double area(Object shape) throws NoSuchShapeException {
if (shape instanceof Square) {
Square s = (Square)shape;
return s.side * s.side;
}
else if (shape instanceof Rectangle) {
Rectangle r = (Rectangle)shape;
return r.height * r.width;
}
else if (shape instanceof Circle) {
Circle c = (Circle)shape;
return PI * c.radius * c.radius;
}
throw new NoSuchShapeException();
}
}
객체 지향적인 도형
// 오버라이드 어노테이션 추가함
public class Square implements Shape {
private Point topLeft;
private double side;
@Override
public double area() {
return side*side;
}
}
public class Rectangle implements Shape {
private Point topLeft;
private double height;
private double width;
@Override
public double area() {
return height * width;
}
}
public class Circle implements Shape {
private Point center;
private double radius;
public final double PI = 3.14159265;
public double area() {
return PI * radius * radius;
}
}
“클래스 C의 메서드 f는 아래의 객체의 메서드만 호출해야 한다”
- 클래스 C
- f가 생성한 객체
- f 인수로 넘어온 객체
- C 인스턴스 변수에 저장된 객체
기차 충돌
// 이렇게 작성하지 말자
final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
// 이렇게 나누자
Options opts = ctxt.getOptions();
File scratchDir = opts.getScratchDir();
final String outputDir = scratchDir.getAbsolutePath();
BufferedOutputStream bos = ctxt.createScratchFileStream(classFileName);