일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- JSP
- LANG
- HTML
- 알고리즘
- jvm
- try&catch
- 암호론
- 자료구조
- 백준
- 클래스 패스
- 형변환 연산자
- 연결된 예외
- 예외처리
- OOP
- 소수판정
- 백준 알고리즘
- BufferedWrite
- 재귀호출기본
- 공개키 암호
- 객체지향
- class
- 자동 형변환
- lang package
- java
- bubble-sort
- 프로그래밍
- 현대암호
- 2884
- 디렉티브
- 객체
- Today
- Total
코드일기장
[Java] 상속과 포함 (객체지향 2-1) 본문
📌상속(Inheritance)이란?
- 기존의 클래스로 새로운 클래스를 작성하는 것 (코드 재사용)
- 두 클래스를 부모와 자식 관계라고 한다.
class 클래스이름 extends 부모클래스{}
기본적으로 새로운 클래스 이름 'extends' 상속해줄 부모 클래스이름{} 이다.
class Parent{
int number;
}
class Child extends Parent{
}
Child 클래스는 Parent 클래스에게 상속받았다. Parent클래스뿐만 아니라 Parent클래스의 부모 즉, Child클래스의 조상의 모든 멤버를 상속받는다. (생성자, 초기화 블록 제외)
결론적으로 자손의 멤버의 개수는 조상의 맴버 개수보다 많거나 같다. (무조건)
위 코드를 보면 Child는 멤버가 0개이지만 사실 상속받은 맴버변수 number로 인해 Child class의 맴버는 1개이다.
class Parent{
int number;
}
class Child extends Parent{
static void children() {
System.out.println("자식만 쓸 수 있는 메서드");
}
}
Child의 클래스 메서드 children은 Parent클래스에서 쓸 수 없다. 반대로 Parent클래스의 맴버가 추가되면 모든 멤버는 Child는 쓸 수 있다.
즉, 조상의 변경은 자손에게 영향이 간다.
자손의 변경은 조상에게 영향이 가지 않는다.
상속의 장점
- 기존의 클래스를 재사용하여 코드의 재사용에 탁월하다. -
- 코드의 중복을 줄일 수 있다. -
🎯 상속 예시 코드
public class Hello {
public static void main(String[] args){
Car c=new Car(4, 4, 40_000_000, "car3");
System.out.printf("%d, %d, %d\n%s\n",c.door,c.wheel,c.price,c.engine_name);
SmartCar sc=new SmartCar(4, 4, 60_000_000, "Scar3");
System.out.println("=========================");
System.out.printf("%d, %d, %d\n%s\n",sc.door,sc.wheel,sc.price,sc.engine_name);
sc.battery=100f;
sc.checkedbattery();
}
}
class Car{ //맴버 5개 (iv 4개 im 1개)
int door;
int wheel;
int price;
String engine_name;
int priceCall(int n){
this.price-=n;
return this.price;
}
public Car(int d,int w,int p,String str){
this.door=d;
this.price=p;
this.wheel=w;
this.engine_name=str;
}
}
class SmartCar extends Car{ // 맴버 7개 (iv 5개 im2개)
float battery;
void checkedbattery(){
System.out.println(battery+"%");
}
public SmartCar(int d,int w,int p,String str) {
super(d,w,p,str);
}
}
📌포함(Composite)이란?
클래스의 멤버로 참조 변수를 선언하는 것
작은 단위 클래스를 조합해서 하나의 커다란 클래스를 만든다.
class Parent{
int age;
}
class C{
String name;
Parent p=new Parent(); //맴버 2개 (name, 참조변수 p)
//명시적 초기화로 p객체 생성 age 저장 공간 생성
}
class C 클래스 안에 Parent p 객체를 생성했다.
public static void main(String[] args){
C c=new C();
c.p.age=400;
System.out.println(c.p.age);
}
C 클래스의 참조변수 p를 이용하려면 출력 부분처럼 c.p.age로 접근한다.
클래스 간의 관계 결정하기
(자바의 정석)
상속: is-a '-은 -이다.'
포함: has-a '-은 -을 가지고 있다.-
🎯 예시 코드
public class Hello {
public static void main(String[] args) {
Circle c1=new Circle();
System.out.println(c1.p.x+" "+c1.p.y+" "+c1.r+" "+c1.color);
Circle c2=new Circle(new Point(60,70), 200);
System.out.println(c2.p.x+" "+c2.p.y+" "+c2.r+" "+c2.color);
}
}
class Point{
int x;
int y;
Point(){}
Point(int x,int y){
this.x=x;
this.y=y;
}
}
class Color{
String color="red";
}
class Circle extends Color{
Point p;
int r;
Circle(){
this(new Point(20, 30),500);
}
Circle(Point p,int r){
this.p=p;
this.r=r;
}
}
20 30 500 red
60 70 200 red
출력 결과
🎈 다음 글 보기 (객체지향2-2)
'Java > OOP' 카테고리의 다른 글
[Java] super, super() (객체지향 2-3) (0) | 2022.01.30 |
---|---|
[Java] 단일상속, 오버라이딩 (객체지향2-2) (0) | 2022.01.26 |
[Java] 생성자와 this(),this (객체지향 1-8) (0) | 2022.01.13 |
[Java] 인스턴스 메서드와 static 메서드, 오버로딩 (객체지향 1-7) (0) | 2022.01.11 |
[Java] 호출 스택, 매개변수 (객체지향 1-6) (0) | 2022.01.04 |