도형을 예로 들면 원 사각형 삼각형 클래스의 공통된 사항들을 포함하는 클래스이다
도형은 실제로 만들어서 사용할수 있는 클래스가 아니라 편의상 공통된 사항들을 포함하는 클래스라 새로 생성할수는 없다
abstract 라는 키워드를 사용한다
클래스의 메소드들 중에서 함수의 형태만 정의하고 실제 함수의 몸체 부분은 정의되지 않은 메소드를
추상 메소드라 한다
1 2 3 4 5 | public abstract class Shape { public abstract double area(); //면적구하기 public abstract double circumference(); //둘레구하기 } |
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 32 33 34 | public class Circle extends Shape { protected int r; public Circle() { r = 0; } public Circle( int r) { this .r = r; } public double circumference() { return Math.PI*2*r; } public double area() { return Math.PI*r*r; } public int getRadius() { return r; } public void setRadius( int r) { this .r = r; } } |
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 32 33 34 35 36 37 38 39 40 41 | public class Rect extends Shape { protected int width, height; public Rect() { this (0, 0); } public Rect( int w, int h) { width = w; height = h; } public double circumference() { return 2*(width+height); } public double area() { return width*height; } public int getWidth() { return width; } public int getHeight() { return height; } public void setSize( int w, int h) { width = w; height = h; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class ShapeUser { public static void main(String[] args) { // TODO Auto-generated method stub Shape shape[] = new Shape[3]; shape[0] = new Circle(5); shape[1] = new Rect(9,5); System.out.println( "shape[0]=" +shape[0].area()); System.out.println( "shape[1]=" +shape[1].area()); } } |