본문 바로가기

JAVA

java #5 상속(업캐스팅, 다운캐스팅, intanceof, 오버라이딩, 추상메소드)

1. 상속
1) 상속이란?
기존의 클래스를 재사용하여 새로운 클래스를 작성하는 것이다. 상속을 통해서 클래스를 작성하면
보다 적은 야의 코드로 새울 클래스를 작성할 수 있고 코드를 공통적으로 관리할 수 있기 때문에 코드의 추가 및
변경이 매우 용이하다.
이러한 특징은 코드의 재사용성을 높이고 코드의 중복을 제거하여 프로그램의 생산성과 유지보수에 크게 기여한다.
새로 작성하고자 하는 클래스의 이름 뒤에 상속받고자 하는 클래스의 이름을 키워드 'extends'와 함께 써주기만 하면 된다.

 class Child extends Parent {
//
}


이 두 클래스는 서로 상속 관계에 있다고 하며, 상속해주는 클래스를 조상클래스라 하고 상속 받는
클래스를 자손 클래스라 한다.

조상 클래스 : 부모(parent) 클래스, 상위(supe) 클래스, 기반(base) 클래스
자손 클래스 : 자식(child) 클래스, 하위(sub) 클래스, 파생된(derived) 클래스

 

2) 자바 상속의 특징
클래스의 다중 상속 지원하지 않음

상속 횟수 무제한

상속의 최상위 조상 클래스는 java.lang.Object 클래스

 

3) 상속과 접근 지정자
a. 자바의 접근 지정자 4가지
public, protected, 디폴트, private
 -> 상속 관계에서 주의할 접근 지정자는 private(클래스 내의 멤버들에게만 접근 허용)
와 protected(다른 패키지에 있어도 서브 클래스는 슈퍼 클래스의 protected 멤버 접근 가능)

 

4)예제 super()를 활용한 ColorPoint 

class Point {
	private int x,y;
	public void set(int x,int y) {
		this.x = x; this.y = y;
	}
	public void showPoint() {
		System.out.println("(" + x + ", " + y + ")");
	}
}
class ColorPoint extends Point {
	private String color;
	public void setColor(String color) {
		this.color = color;
	}
	public void showColorPoint() {
		System.out.print(color);
		showPoint();
	}
}
public class ColorPointEx {
	public static void main(String[] args) {
		Point p = new Point();
		p.set(1, 2);
		p.showPoint();
		
		ColorPoint cp = new ColorPoint();
		cp.set(3, 4);
		cp.setColor("red");
		cp.showColorPoint();

	}

}

 


2. 업캐스팅
1) 업캐스팅이란?
서브 클래스 객체를 슈퍼 클래스 타입으로 타입 변환

2)업캐스팅된 레퍼런스
객체 내에 슈퍼 클래스의 멤버만 접근 가능

 

3. 다운캐스팅
1) 다운캐스팅이란?
슈퍼 클래스 객체를 서브 클래스 타입으로 변환
개발자의 명시적 타입 변환 필요

4. instanceof 
1) instanceof 연산자란?
레퍼런스가 가리키는 객체의 타입 식별을 위해 사용


2) 사용법
객체레퍼런스 instanceof 클래스타입
연산의 결과 : true/false의 불린 값

3) 예제 instanceof 연산자 활용

class Person3{}
class Student3 extends Person3{}
class Researcher extends Person3 {}
class Professor extends Researcher {}

public class InstanceOfEx {
	static void print(Person3 p) {
		if(p instanceof Person3)
			System.out.print("Person ");
		if(p instanceof Student3)
			System.out.print("Student ");
		if(p instanceof Researcher)
			System.out.print("Researcher ");
		if(p instanceof Professor)
			System.out.print("Professor ");
	}

	public static void main(String[] args) {
		System.out.println("new Student () -> \t"); print(new Student3());
		System.out.println("new Researcher () -> \t"); print(new Researcher());
		System.out.println("new Professor () -> \t"); print(new Professor());

	}

}


5. 메소드 오버라이딩
1) 메소드 오버라이딩이란? 

a.메소드 오버라이딩(Method Overriding)

슈퍼 클래스의 메소드를 서브 클래스에서 재정의

슈퍼 클래스 메소드의 이름, 매개변수 타입 및 개수, 리턴 타입 등 모든 것 동일하게 작

메소드 무시하기, 덮어쓰기로 번역되기도 함

동적 바인딩 발생

서브 클래스에 오버라이딩된 메소드가 무조건 실행되는 동적 바인딩



2) 오버라이딩의 목적

a.수퍼 클래스에 선언된 메소드를, 각 서브 클래스들이 자신만의 내용으로 새로 구현하는 기능

b.상속을 통해 '하나의 인터페이스(같은 이름)에 서로 다른 내용 구현'이라는 객체 지향의 다형성 실현

Line 클래스에서 draw()는 선을 그리고

Circle 클래스에서 draw()는 원을 그리고

Rect 클래스에서 draw()는 사각형 그리고



3) 오버라이딩 vs 오버로딩



6. 추상 메소드와 추상 클래스
1) 추상 메소드란?

추상 메소드(abstract method)

선언되어 있으나 구현되어 있지 않은 메소드, abstract로 선언

추상 메소드는 서브 클래스에서 오버라이딩하여 구현해야 함

 


2) 2가지 종류의 추상 클래스 사례

a.추상 메소드를 하나라도 가진 클래스

클래스 앞에 반드시 abstract라고 선언해야 함

 

b. 추상 메소드가 하나도 없지만 abstract로 선언된 클래스