본문 바로가기

언어/Java

상속(Inheritance)

※ 상속은 클래스 간에 계층 구조를 형성하여 속성과 메서드를 공유하고 재사용하는 개념

부모 클래스(상위 클래스)의 속성과 메서드를 자식 클래스(하위 클래스)가 물려받아 사용할 수 있도록 합니다.

class Vehicle {
    // 부모 클래스의 속성과 메서드 정의
}

class Car extends Vehicle {
    // 자식 클래스에서 추가적인 속성과 메서드 정의
}

 

UML 방식, 공통점이 있다고 무조건 상속하는건 X

ssn : 주민번호

자식 IS A 부모 
  (kind of)
자식은 부모의 한 종류이다라는 관계가 논리적으로 성립이 되어야함.
ex) 고객 is a 사람 ○ 사람이다/사람의 한 종류이다
      사원 is a 사람 ○
      계좌 is a 사람 X

      계좌 HAS A 사람 관계가 성립되어야함

 

부모-자식 관계가 성립되면 부모 쪽 함부로 변경하면 안됨. 자식도 함께 변경되기 때문

자식 클래스는 부모 클래스의 모든 멤버에 접근이 가능하며, 자신만의 추가적인 멤버들을 정의할 수도 있다.

class Shape{ // 컴파일시 class Shape extends Object{}  로 바뀜.                               
//	private double area;
	protected double area;
	double getArea() {
		return area;
	}
}

class Circle extends Shape { // shape로부터 확장된/상속받는 class이다. 자식 쪽에서 부모를 결정한다. 부모로부터 상속받으면 자식 class가 간결해짐. 재사용성이 높아짐.
	
	private int radius;
	
	Circle(int radius) {
		this.radius = radius;
	}

	int getRadius() {
		return radius;
	}
		
	void makeArea() {
		area = 3.14 * radius * radius;
	}
}

class Rectangle extends Shape {
	private int width, length;
	
	Rectangle(int width, int length) {
		this.width = width;
		this.length = length;
	}
	
	void makeArea() {
		area = width * length;
	}
}


public class ShapeTest {	//=public class ShapeTest extends Object{}
	//실행 시에 필요한 로드된 클래스 갯수 : public, object, string[], circle, system, rectangle 6개

	public static void main(String[] args) {
		Circle c = new Circle(5); // 반지름이 5인 원객체
		System.out.println(c.getRadius());	//5
		c.makeArea(); //원의 면적을 계산한다.
		System.out.println(c.getArea()); //면적값 X.XXXX
		
		Rectangle r = new Rectangle(3, 4); //가로3, 세로4인 사각형객체
		r.makeArea(); // 사각형의 면적을 계산한다
		System.out.println(r.getArea()); // 면적값 12.0
	
	}
}

결과

 

부모영역인 shape부터 먼저 할당된다
실제로는 Object도 있다
부모의 private 변수도 자식에게 물려진다 그러나 자식이 직접 접근을 못함

※ 자바최상위 클래스

System 위에도 Object 있음
java lang 라이브러리 최상위 패키지


java.lang.Object

   hashCode(): int 객체를 식별해주는 객체정보값, 해시 코드 값이 같으면 같은 객체, 객체정보를 숫자로
   equals(Object):boolean, 객체가 같은가 다른가
    toString(): String, 객체정보를 문자로

                     // getClass().getName() + '@' + Integer.toHexString(hashCode()) @뒤를 16진수 값으로 리턴

public class ObjectTest {
	
	public static void main(String[] args) {
		Object o1;
		Object o2;
		Object o3;
		o1 = new Object();
		o2 = new Object();
		o3 = o1;
		System.out.println(o1.hashCode());
		System.out.println(o2.hashCode());
		System.out.println(o3.hashCode());
		
		System.out.println(o1 == o2); //false
		System.out.println(o1 == o3); //true
		
		System.out.println(o1.equals(o2)); //false
		System.out.println(o1.equals(o3)); //true

		// true if this object is the same as the obj argument; false otherwise.
		// this object는 o1이 참조하는 객체, obj argument가 o3
		
		System.out.println(o1.toString()); //java.lang.Object@123772c4
		
		Circle c1, c2;
		c1 = new Circle(5);
		c2 = new Circle(5);	// 부모의 부모인 object로부터 상속 받을 수 있다. 상속의 깊이가 깊을 수록 변수가 재선언될 수 있다.
		System.out.println(c1.toString()); //Circle@73a28541 (@ 뒤 16진수)
		System.out.println(c2.toString()); //Circle@6f75e721
		System.out.println(c1.equals(c2)); //false  
	}
}

결과

'언어 > Java' 카테고리의 다른 글

오버라이딩(Overriding)과 다형성(Polymorphism)  (0) 2023.07.31
상속 예제  (0) 2023.07.31
싱글톤  (0) 2023.07.31
패키지  (0) 2023.07.31
Product 예제 1  (0) 2023.07.31