[상속-18] abstract

seratpfk·2022년 8월 2일
0

JAVA

목록 보기
68/96

Shape 클래스

public class Shape {
	private String type;
	public Shape(String type) {
		super();
		this.type = type;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public double getArea() {
		return 0;
	}

Circle 클래스

public class Circle extends Shape {
	private double radius;
	public Circle(String type, double radius) {
		super(type);
		this.radius = radius;
	}
	@Override
	public double getArea() {
		return Math.PI * Math.pow(radius, 2);
	}
}

Main 클래스

public class Main {
	public static void main(String[] args) {
		Shape s1 = new Shape("도형");
		System.out.println(s1.getType());
		System.out.println(s1.getArea());
		Shape s2 = new Circle("원", 1);
		System.out.println(s2.getType());
		System.out.println(s2.getArea());
	}
}
  • Shape 클래스타입의 객체는 존재할 수 없는 객체이다.
  • abstract 처리해서 객체의 생성을 막을 수 있다.

추상 메소드

  1. 본문이 없는 메소드
  2. 호출용으로 사용되는 메소드
  3. 중괄호{} 자체를 없애고 세미콜론(;)을 추가함
  4. public abstract(추천) 또는 abstract public

추상 클래스

  1. 추상 메소드가 1개 이상 존재하는 클래스
  2. public abstract class
  3. 본문이 없는 메소드를 포함하기 때문에 객체 생성이 불허됨
  4. 추상 클래스를 상속 받는 클래스는 "반드시" "모든" 추상 메소드를 오버라이드 해야 함

Shape 클래스

public class Shape {
  • 추상클래스로 바꿔준다.
public abstract class Shape {

Shape 클래스

	public double getArea() {  
		return 0;
	}
  • 추상메소드(본문이 없는 메소드)로 바꿔준다.
	public abstract double getArea();

Main 클래스

		Shape s1 = new Shape("도형");
		System.out.println(s1.getType());
		System.out.println(s1.getArea());
  • 객체생성이 불허되어 출력되지 않음.

출력:

3.141592653589793

0개의 댓글