Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- SQL
- 자바파일업로드
- 파일업로드
- html5
- MariaDB
- jquery
- 자바스크립트
- insert
- mybatis
- 퍼블리싱
- ORDERBY
- poi엑셀
- 자바타입
- 자바
- poi
- 게시판구현
- JSTL
- 페이징
- crud
- pagenation
- mysql
- spring
- jsp
- 스프링파일업로드
- 스프링
- PAGING
- CSS3
- select
- db
- Java
Archives
- Today
- Total
째의 개발 기록방
[Java/Spring] 업캐스팅과 다운캐스팅 본문
자바에서 업캐스팅(Upcasting)과 다운캐스팅(Downcasting)이란 무엇일까?
캐스팅(casting)이란 타입을 변환하는 것을 말하며 형변환이라고도 한다.
자바에서 서브 클래스는 수퍼 클래스의 모든 특성을 상속받는다. 그렇기 때문에 서브 클래스는 수퍼 클래스로 취급될 수 있다.
여기서 업캐스팅(Upcasting)이란 서브 클래스의 객체가 수퍼 클래스 타입으로 형변환되는 것을 말한다.
(자식 클래스의 객체가 부모 클래스 타입으로 형변환 되는 것)
그렇다면 업캐스팅은 왜 사용하는 것일까? 업캐스팅을 사용하는 이유는 다형성(Polymorphism)과 관련이 있다.
class Person{
String name;
Person(String name){
this.name = name;
}
}
class Student extends Person{
String check;
Student(String name){
super(name);
}
}
public class Main{
public static void main(String[] args){
Student s = new Student("홍길동");
Person p = s; // 업캐스팅
p.name = "이름이다.";
p.check = "컴파일 에러 발생"; // 컴파일 에러 발생
}
}
다운캐스팅(Downcasting)이란
업캐스팅과 반대로 캐스팅 하는 것을 다운캐스팅이라고 한다. 업캐스팅된 것을 다시 원상태로 돌리는 것을 말한다. 하위 클래스로의 다운캐스팅을 할때는 타입을 명시적으로 지정해줘야한다는 특징이 있다.
아래 코드를 보면 Student s = (Student)p; 라고 나오는데 이 부분이 바로 다운캐스팅이다.
class Person{
String name;
Person(String name){
this.name = name;
}
}
class Student extends Person{
String check;
Student(String name){
super(name);
}
}
public class Main{
public static void main(String[] args){
Person p = new Student("홍길동");
Student s = (Student)p; // 다운캐스팅
s.name = "김유신";
s.check = "check!";
}
}
출처:https://madplay.github.io/post/java-upcasting-and-downcasting,https://computer-science-student.tistory.com/335
'Back End > Java, Spring' 카테고리의 다른 글
[Java/Spring] 자주 사용되는 어노테이션(Annotation)과 Lombok (0) | 2022.02.10 |
---|---|
[Java/Spring] 파일업로드(File_Upload) (0) | 2021.12.11 |
[Java/Spring] 파일다운로드(File_download) (0) | 2021.12.07 |
[Java/Spring] Poi 엑셀 파일 업로드(Excel _file_Upload) (0) | 2021.11.22 |
[Java/Spring] Poi 엑셀 파일 다운로드(Excel _file_Download) (0) | 2021.11.18 |