[Java] 상속

Jinsung·2021년 5월 27일
0

JAVA

목록 보기
10/12
post-thumbnail

상속

자바에서도 부모클래스(parent class)로부터 상속받은 자식클래스(children class)는 부모클래스의 모든 자원과 메서드 등을 자신의 것 처럼 사용 할 수 있습니다.

extends 이용한 상속

상위 클래스

package inheritance;


public class Parants {
	
	public Parants() {
		System.out.println("부모");
	}
	
	public void Parantsout () {
		System.out.println("out");
	}
}

하위 클래스

package inheritance;

public class Child extends Parants { // extends 이용 상속
	
	public Child() {
		System.out.println("자식");
	}
	public void ChildClass() {
		System.out.println("끝");
	}

}

메인 클래스

package inheritance;

public class MainClass {
	
	public static void main(String[] args) {
		Child cd = new Child();
		
		cd.Parantsout(); // 자식에서 상속받아기 때문에 불러올수 있다
		cd.ChildClass();
	}
}

결과값
부모
자식
out

메서드 오버라이드:Override

부모 클래스의 기능을 자식 클래스에서 재정의 해서 사용한다.

상위 클래스

package inheritance;


public class Parants {
	
	public Parants() {
		System.out.println("부모");
	}
	
	public void Parantsout () {
		System.out.println("out");
	}
}

하위 클래스

package inheritance;

public class Child extends Parants { // extends 이용 상속
	
	public Child() {
		System.out.println("자식");
	}
	public void Parantsout() {
		System.out.println("끝");
	}

}

메인 클래스

package inheritance;

public class MainClass {
	
	public static void main(String[] args) {
		Child cd = new Child();
		
		cd.Parantsout(); // 오버라이드
	}
}

오버라이드 자료형(타입)

상위 클래스

package inheritance;


public class Parants {
	
	public void Parantsout () {
		System.out.println("out");
	}
}

하위1 클래스

package inheritance;

public class FirstChild extends Parants {
	
	public void Parantsout() {
		
		System.out.println("---Frist id ");
		
	}

}

하위2 클래스

package inheritance;

public class SecondChild extends Parants {
	
	public void Parantsout() {
		
		System.out.println("---Second id ");
		
	}

}

메인 클래스

package inheritance;

public class MainClass {
	
	public static void main(String[] args) {
		
		Parants childs[] = new Parants[2];
		childs[0] = new FirstChild();
		childs[1] = new SecondChild();
		
		for(int i = 0; i < childs.length; i++) {
			childs[i].Parantsout();
		}
		
	}
}

결과값
---Frist id
---Second id

Tip

자바에서 Ctrl + T 를 누르면 상속관계를 확인할수 있다.(확인 시 모든 클래스의 최상위에는 Object 클래스가 있다.)

Super

상위 클래스를 호출할때 super 키워드 이용

상위 클래스

package inheritance;


public class Parants {
	
	int year = 1994;
	
	public void Parantsout () {
		System.out.println("out");
	}
}

하위 클래스

package inheritance;

public class FirstChild extends Parants {
	
	int year = 2021;
	
          public void getYear()  {
			System.out.println(this.year); // this로 클래스 안의 변수값 불러오기
			System.out.println(super.year); // 상위 클래스에서 변수값 불러오기
		
	}

}

메인 클래스

package inheritance;

public class MainClass {
	
	public static void main(String[] args) {
		
		FirstChild fc = new FirstChild();
		
		fc.getYear();
		
	}
}

결과값
2021
1994

0개의 댓글