[JAVA] 상속 - 3

김나영·2022년 8월 2일
0
post-thumbnail

**
Person 타입 → Person 호출.실행 = 정적바인딩 ( C++ )
Person 타입 → Person 호출, new Student() 실행 → Student 호출 = 동적바인딩


추상클래스 (Abstract)

* 추상메소드 (Abstract Method)

  • 선언되어 있으나 본문이 없는 메소드
  • 호출용으로 사용되는 메소드
  • 중괄호{} 자체를 없애고 세미콜론(;)을 추가함
  • 메소드 선언 앞에 abstrct 키워드를 붙임
  • public abstract(추천) 또는 abstract public

* 추상클래스 (Abstract Class)

  • 추상메소드가 하나 이상 포함된 클래스
  • 구체적이지 않고 추상적인 단어들은 추상클래스로 구현 가능
  • 클래스 앞에 abstract 키워드를 붙임
  • public abstract class
  • 본문이 없는 메소드를 포함하기 때문에 객체 생성이 불허됨
  • 추상 클래스를 상속 받는 클래스는 반드시 모든 추상 메소드를 오버라이드 해야함

-Shape 클래스

public abstract 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 abstract double getArea();    // Shape을 상속 받는 객체들이 호출할 때 사용하는 메소드 
										 // 사용되지는 않는다.    ->  추상 메소드로 바꿔준다. ( 본문이 없는 메소드 )
}

-Circle 클래스

public class Circle extends Shape{	
	//필드
	private double radius;
	//생성자
	public Circle(String type, double radius) {
		super(type);
		this.radius = radius;
	}
	// Shape 클래스는 추상 클래스 이므로, 반드시 double getArea() 메소드를 오버라이드 해야 함	
	@Override
	public double getArea() {
		return Math.PI * Math.pow(radius, 2);		
	}	
}

-Main 클래스

public class Main {
	public static void main(String[] args) {		
		// Shape 클래스타입의 객체는 존재할 수 없는 객체이다.
		// abstract 처리해서 객체의 생성을 막을 수 있다.	
		/*
		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());
	}
}
profile
응애 나 애기 개발자

0개의 댓글