코드일기장

[Java] 상속과 포함 (객체지향 2-1) 본문

Java/OOP

[Java] 상속과 포함 (객체지향 2-1)

codeStudy123 2022. 1. 20. 21:00

 

 


📌상속(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)



 

 

Comments