글쓴이 :자사인 1999년 10월 11일 10:34:19
추상클래스를 아래와 같이 선언하고
public abstract class Shape {
public abstract double area();
public abstract double circumference();
}
추상클래스를 상속받는 서브클래스(Circle,Rectangle)는 다음과 같을때
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;
}
}
class Rectangle extends Shape{
protected int width,height;
public Rectangle(){
width=0;
height=0;
}
public Rectangle(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;
}
}
메인함수를 호출하는 클래스는
class ShapeUser {
public static void main(String args[]){
Shape shape[]=new Shape[3];
shape[0]=new Circle(5);
shape[1]=new Circle(7);
shape[2]=new Rectangle(9,5);
System.out.println("shape[0]'s area=" +shape[0].area());
System.out.println("shape[1]'s area="+shape[1].area());
System.out.println("shape[2]'s area="+shape[2].area());
}
}
이렇게 되어있는 소스입니다.
근데 제가 묻고 싶은 것은 ShapeUser 클래스에서 Shape를 상속받는 선언없이 어떻게 Shape 객체를 생성할 수 있는냐 입니다.(진짜 초보적인 질문이지요?)
그것이 Shape클래스가 public 으로 선언되어있기 때문인가요? 그렇다 하더라도 Shape 의 객체를 생성하거나 메소드를 사용하기 위해서는 먼저 상속을 받아야 하는 것이 아닌지.. 하여간 너무 초보적인 질문이라고 외면하지 마시고 좀 알려주세요..