TIL/남궁성의 자바의 정석
자바의 정석 ch7-1,2 상속
minOE
2023. 11. 19. 18:20
728x90
상속(inheritance)
- 기존의 클래스로 새로운 클래스를 작성하는 것 (코드의 재사용)
-두 클래스를 부모와 자식으로 관계를 맺어 주는 것
형태
class 자식클레스 extends 부모클래스 {
}
예시
class Parent {}
class Child extends Parent {
//..
}
- 자손은 조상의 모든 멤버를 상속 받는다 (생성자,초기화 블럭 제외)
-자손의 멤버 개수는 조상보다 적을 수 없다.
class Parent{ int age; } class Child extends Parent{ void play(){ System.out.println("놀자"); } } public class Main { public static void main(String[] args) { Child child = new Child(); child.play(); System.out.println(child.age); } }
출력값
상속을 받지 않는 경우
class Point3D { int x; int y; int z; } public class Main { public static void main(String[] args) { Point3D point3D = new Point3D(); point3D.x =3; point3D.y =7; point3D.z =5; System.out.printf("%d %d %d",point3D.x,point3D.y,point3D.z); }
출력값
상속을 받는 경우
class Point { static int x =3 ; static int y =7; } class Point3D extends Point { int z; } public class Main { public static void main(String[] args) { Point3D point3D = new Point3D(); point3D.z =5; System.out.printf("%d %d %d \n", point3D.x,point3D.y,point3D.z); Point.x=2; Point.y=9; System.out.printf("%d %d %d", point3D.x,point3D.y,point3D.z); } }
출력값
요약
자식 클래스는 부모 클래스로 부터 영향을 받는다.
그러나 부모 클래스는 자식 클래스에게 영향을 받지 않는다.
728x90