본문 바로가기

[JAVA] 추상클래스

반응형

객체(인스턴스)를 생성할 수 없는 클래스

용도 : 동일한 메소드로 접근 가능한 서브 클래스를 설계하기 위함

작업명세표 역할>>> 여러 가지 작업들을 공통된 규정으로 묶고 싶을 때 사용하면 된다.

단지 상속을 통해 서브 클래스에 완성될 수 있도록 한다.

   

도형을 그리는 추상클레스(Shape).

자식클래스인 원, 삼각형, 사각형 각각 넓이를 구하는 방법은 다름.

면적을 구하는 방법은 다르지만 , 부모인 Shape가 면적을 구하라고 지시할 때는 동일한 메소드로 지시할 수 있도록 하기 위해서 면적을 구하는 메소드를 추상 메소드로 정의해 둔다. 그리고 Shape는 추상 클래스로 정의한다.

   

   

   

//import java.awt.Shape;

   

abstract class Shape  //추상클래스

{

  protected double area;  //면적을 저장할 도형의 공통된 필드

    

  public double getArea()  //면적 값을 알려주는 메소드

  {

    return area;

  }

  abstract public void calcArea();  //도형의 면적을 구하기 위한 추상메소드

}

   

class Circle extends Shape

{

  protected int radius;

    

  public Circle()

  {

      

  }

    

  public Circle(int radius)

  {

    this.radius = radius;

  }

    

  public void calcArea()  //오버라이딩

  {

    area =  radius*radius*Math.PI;

  }

}

   

class Rectangle extends Shape

{

  protected int width;

  protected int height;

    

  public Rectangle()

  {

    

  }

    

  public Rectangle(int width, int height)

  {

    

    this.width = width;

    this.height = height;

  }

    

  public void calcArea()//오버라이딩

  {

    area = width*height;

  }

   

}

   

class Triangle extends Shape

{

  protected int width;

  protected int height;

   

  public Triangle()

  {

      

  }

    

  public Triangle(int width, int height)

  {

    this.width = width;

    this.height = height;

  }

    

  public void calcArea()//오버라이딩

  {

    area = width*height;

  }

}

   

public class AbstractTest

{

  public static void main(String[] args)

  {

    Shape[]sha  = new Shape[3];

    sha[0= new Circle(5);

    sha[1= new Rectangle(58);

    sha[2= new Triangle(10 , 15);

      

    for(int i=0; i < sha.length; i++)

    {

      sha[i].calcArea();

      System.out.println("도형의 넓이:"+sha[i].getArea());

        

    }

   

  }

}

   

   

   

   

   

반응형

'About 프로그래밍!!! > JAVA' 카테고리의 다른 글

[java]try-catch-finally로 예외처리  (0) 2010.08.23
[java] 생성자 만들기 예제.  (0) 2010.08.17
[JAVA] 버블소트, 퀵소트  (0) 2010.07.29
[JAVA] 문제풀이(쌤이 짠 코드)  (0) 2010.07.29
[JAVA]문제풀기  (0) 2010.07.28
-->