JAVA
day08)상속
code_learner
2021. 12. 31. 01:09
상속이란?
: 부모클래스의 기능을 자식클래스가 물려받는 것, 부모클래스에서 작성한 기능의 재사용을 위해 사용한다.
class Point {//부모클래스
int x;
int y;
public Point(int x, int y) {//인자, input, 파라미터 => 외부에서 넘어온 값
this.x=x;//외부에서(사용자가) 넘어온 값을 멤버변수로 초기화!
this.y=y;
}
void info() {
System.out.println("점 ("+this.x+","+y+")");
}
}
class ColorPoint extends Point{//자식클래스
String color;
ColorPoint(int x, int y) {
super(x, y);//나는 this, 부모는 super
//자식클래스의 모든 생성자들은,
//가장 처음에 부모클래스의 기본 생성자를 호출하려고 한다!
//생성자 끼리 상속이 안된다고 보고, super를 통해 접근이 가능하다고 생각하는 것이 편하다.
}
void move() {
this.x++;//부모 클래스를 가지고와서 자식클래스에서 사용
this.y++;//=> 멤버변수와 메서드는 모두 자식클래스에 존재
}
}
public class Test04 {
public static void main(String[] args) {
ColorPoint cp = new ColorPoint(1,2);
cp.move();
cp.info();
}
}
오버라이딩
오버로딩
-상속xxx
-메서드 시그니쳐가 다름
-함수명 중복정의 허용
-메서드에서 자주 사용됨
오버라이딩
-상속o
-메서드 시그니쳐가 같아야함
-메서드 재정의
-기존의 메서드는 사용할 수 없음
업캐스팅
: 자식클래스의 객체가 부모클래스의 참조 변수로 형 변환 되는 것
<구조>
부모클래스 변수 = 자식 객체값
package day25;
class Human{
String name;
int age;
String major;
public Human(String name, int age, String major) {
this.name=name;
this.age=age;
this.major=major;
}
void info() {
System.out.println("name: "+name);
System.out.println("age: "+age);
System.out.println("hobby: "+major);
}
}
class Student extends Human{
int grade;
public Student(String name, int age, String major, int grade) {
super(name, age, major);
this.grade = grade;
}
void info() {
super.info();
System.out.println("grade: "+grade+"학년");
}
void study() {
System.out.println("공부중!");
}
}
public class Upcasting {
public static void main(String[] args) {
Human h = new Student("아무무", 20, "JAVA", 1);
//System.out.println(h.grade);
//업캐스팅 되었기 때문에 Human클래스의 객체 변수는 grade를 저장할 수 없다.
//h.study();
//업캐스팅 되었기 때문에 study()메서드를 호출 할 수 없다.
h.info();
//하지만 info()호출시 Student 클래스의 info()메서드가 호출된다.
// :동적바인딩!★★★
/*결과
name: 아무무
age: 20
hobby: JAVA
grade: 1학년*/
}
}
*동적바인딩*
컴파일 시점에선 부모클래스의 필드로 인지하나, 런 타임 시점에선 자식클래스의 필드로 호출 할 메서드를 묶는 것
이를 통해 다형성이 실현되게 된다.
*다형성*
같은 메서드를 사용해도 객체에 따라 결과의 값이 달라지는 현상
ex)
돼지.안녕(); -> 꿀꿀
고양이.안녕() -> 야옹