기본 구조
class 하위클래스 이름 extends 상위클래스 이름 {} //상위 클래스 ⊂ 하위 클래스 의 형태가 됨.
ex)
class Parent{
private int a = 0; //private 멤버 정의
int b= 5;
}
class Child extends Parents{
int c= 10; //하위클래스 자신만의 멤버 추가
public void play(){
system.out.println(a); // private 영역은 실행이 되지 않음.
system.out.println(b); // 상위 클래스 에서 상속 받은 멤버
system.out.println(c);
}
}
public class Inheritance_1{
public static void main(String[] args){
Child ch = new Child();
ch.play();
}
}
실행 결과
5
10
★ Object class
: 모든 클래스의 상위 클래스
==> 별도로 extends 를 사용하지 않아도 자동으로 Object class의 모든 필드와 메소드를 상속받음
ex)
calss Parents {
int a;
Parents(){ a=1; } // 파라미터값을 받지 않는 default생성자
Parents(int x) { // 파라미터값을 받는 일반 생성자
a= x;
}
}
calss Child extends Parents{
int b; // 하위 클래스 고유의 멤버
Child(){ // 하위 클래스의 생성자
super(); //상위 클래스의 default생성자를 불러옴
//super(20); //초기화 값을 정해서 불러온다면 a는 20으로 출력됨.
b= 10;
}
}
public void play(){
system.out.println(a);
system.out.println(b);
}
}
public class Inheritance_1{
public static void main(String[] args){
Child ch = new Child();
ch.play();
}
}
실행 결과
1
10
: super() 메소드가 상위 클래스의 생성자를 불러온다면 super 키워드는 상위 클래스의 멤버에 직접 접근하는 방법.
: 하위 클래스의 멤버와 상위클래스의 멤버의 이름이 같을 경우 구분하기 위해 인스턴스메소드 에서만 사용가능.
ex)
class Parent {
int a = 10; //상위 클래스 멤버 a
}
class Child extends Parent {
int a = 20; //하위 클래스 멤버 a
public void display() {
System.out.println(a); //하위 클래스 멤버 a 호출
System.out.println(this.a); //같은 클래스 내의 멤버 a 호출
System.out.println(super.a); //상속받은 상위 클래스의 멤버 a 호출
}
}
public class Inheritance_2 {
public static void main(String[] args) {
Child ch = new Child();
ch.display();
}
}
실행 결과
20
20
10
: 상속관계에 있는 상위 클래스에서 이미 정의되었던 메소드를 하위 클래스에서 필요에 의해 다시 재정의 하는것.
★ 오버로딩과의 차이점
: 오버로딩은 새로운 메소드를 생성 하는것.
: 오버라이딩은 상속받은 기존의 메소드를 변형하여 재정의 하는것.
ex)
class Parent {
void display() {
System.out.println("상위 클래스의 display() 메소드입니다.");
}
}
class Child extends Parent {
void display() { //메소드 오버라이딩
System.out.println("하위 클래스의 display() 메소드입니다.");
}
void display(String n) { // 메소드 오버로딩
System.out.println(n);
}
}
public class Inheritance05 {
public static void main(String[] args) {
Parent pa = new Parent();
pa.display();
Child ch = new Child();
ch.display();
ch.display("오버로딩된 display() 메소드입니다.");
}
}
실행결과
상위 클래스의 display()메소드 입니다.
하위 클래스의 display()메소드 입니다.
오버로딩된 display() 메소드 입니다.