본문 바로가기
Programming/Java

[Java] 상속(Ingerit)

by AI_Wooah 2022. 3. 7.

상속이란?

다른 클래스가 가지고 있는 멤버(필드와 메소드)들을 새로 작성할 필요 없이 클래스에서 직접 만들지 않고 가져와서 사용한다.

부모 클래스가 가진 필드와 메소드 그리고 타입을 물려준다

자식 클래스는 그것을 받아서 자신의 것처럼 사용할 수 있다.

상속의 목적

상속의 장점

적은 양의 코드로 새로운 클래스를 작성 가능하다

코드를 공통적으로 관리하기 때문에 여러 코드의 추가 및 변경이 용이하다

중복을 제거해서 생산성과 쉬운 유지보수성에 크게 기여한다.

작성 방법

클래스간의 상속시에는 extends 키워드를 사용한다.

extends 뒤에 한개의 클래스명만 작성 가능하다(단일상속)

표현식

[접근제한자] class 클래스명 extends 클래스명{}
상속받는 클래스
후손클래스
자식클래스
파생클래스
서브클래스
상속하는 클래스
상위클래스
부모클래스
선조클래스
슈퍼클래스

단일상속(Single ingeritance)

기본적으로 자바에서는 다중상속을 지원하지 않고 단일상속만 지원한다.

다중상속(Multiple ingeritance)

Is a 상속관계

자식클래스는 하나의 부모클래스일 수 있다.

public class Circle extends Shape {
	private int x; //중심점의 x좌표
	private int y; //중심점의 y좌표
	private int r; // 반지름 Radius
}

public class Shape{
	private double area;
	public void calcArea(){
		//넓이구하기 메소드
	}
}

Has a 포함관계

상속과 비슷하나 상속은 아니다.

참조하고 있다는 뜻

public class Shape{
	private int x; //중심점의 x좌표
	private int y; //중심점의 y좌표
	private int r; // 반지름 Radius
}

public class Circle extends Shape {
	private Point center = new Point();
}
public class Point(){
	private int x; //중심점의 x좌표
	private int y; //중심점의 y좌표
}

Has a 포함/Is a 상속

public class Shape{
	private double area;
	public void calcArea(){
		//넓이구하기 메소드
	}
}

public class Circle extends Shape {
private Point center = new Point();
public class Point(){
private int x; //중심점의 x좌표
private int y; //중심점의 y좌표

상속의 특징

  1. 부모클래스의 생성자, 초기화블럭은 상속 안됨
  • 후손클래스 객체 생성시, 부모클래스 생성자가 먼저 실행되도록 되어 있음.
  • 후손클래스 생성자 안에서 부모클래스 생성자 호출을 명시하고 싶으면 super();를 입력함
  1. 부모의 private 멤버는 상속은 되지만 접근 불가능하다
  • 접근 제한범위는 상속 받은 경우에 나 자신만 가능하기 때문에 외부에서 접근 불가능한 것을 말한다.
  • 후손 객체 생성시에 부모의 필드값도 전달받은 경우, 후손 생성자 안에서 부모의 private 필드에 직접 초기값 대입 못함
  • 전달받은 부모 필드값을 부모생성자 쪽으로 넘기는 방법을 이용한다.

예시) super(전달받을값, ...); //부모의 매개변수 있는 생성자를 통한 초기화

  1. 모든 클래스는 Object 클래스의 후손
  • Object클래스가 제공하는 메소드를 오버라이딩해서 메소드 본래 기능을 변경할 수 있음.
  • 모든 클래스는 java.lang.Object를 포함하고 있으며 jvm이 자동으로 추가해준다.

예시) java.lang.String 클래스의 equals()과 toString()

super()

후손 객체 생성시에 만드는 것

가장 첫 줄에 생략돼있다.

public class Member{
	public Member(){
		super();
	}
}

super.

상속을 통한 자식 클래스를 정의할 때 해당 자식 클래스의 부모 객체를 가리킨다.

오버라이딩(overriding)

부모가 가지고 있는 메소드를 내가 덮어쓰는 것을 말한다.

부모에게서 가지고 온 기능을 변경할 수 있다.

오버라이딩(overriding) 성립 요건

부모 클래스의 메소드와 자식 클래스의 메소드 비교 
- 이름이 동일해야 한다. 
- 매개변수의 개수와 타입, 순서가 동일해야 한다. 
- 리턴 타입이 동일해야 한다. 
- private 메소드의 오버라이딩은 불가하다.

상속의 편리함을 알아보기 위한 코드 연습

Desktop

package com.kh.inherit.part01_inheritTest.beforeProduct.model.vo;

import java.util.Date;

public class Desktop {
	private String brand;
	private String productNumber;
	private String productCode;
	private String productName;
	private String cpu;
	private int hdd;
	private int ram;
	private String operationSystem;
	private int price;
	private Date manufacturingDate;
	private boolean allInOne;
	
	public Desktop() {}
	
	
	//모든 필드를 초기화하는 생성자
	public Desktop(String brand, String productNumber, String productCode, String productName, String cpu, int hdd, int ram, String operationSystem, int price, Date manufacturingDate, boolean allInOne) {
		this.brand = brand;
		this.productNumber = productNumber;
		this.productCode = productCode;
		this.productName = productName;
		this.cpu = cpu;
		this.hdd = hdd;
		this.ram = ram;
		this.operationSystem = operationSystem;
		this.price = price;
		this.manufacturingDate = manufacturingDate;
		this.allInOne = allInOne;
		
	}
	
	//setter & getter
	public void setBrand(String brand) {
		this.brand = brand;
	}
	
	public void setProductNumber(String productNumber) {
		this.productNumber = productNumber;
	}
	
	public void setProductCode(String productCode) {
		this.productCode = productCode;
	}
	
	public void setProductName(String productName) {
		this.productName = productName;
	}
	
	public void setCpu(String cpu) {
		this.cpu = cpu;
	}
	
	public void setHdd(int hdd) {
		this.hdd = hdd;
	}
	
	public void setRam(int ram) {
		this.ram = ram;
	}
	
	public void setOperationSystem(String operationSystem) {
		this.operationSystem = operationSystem;
	}
	
	public void setPrice(int price) {
		this.price = price;
	}
	
	public void setManufacturingDate(Date manufacturingDate) {
		this.manufacturingDate = manufacturingDate;
	}
	
	public void setAllInOne(boolean allInOne) {
		this.allInOne = allInOne;
	}
	
	public String getBrand() {
		return brand;
	}
	
	public String getProductNumber() {
		return productNumber;
	}
	
	public String getProductCode() {
		return productCode;
	}
	
	public String getProductName() {
		return productName;
	}
	
	public String getCpu() {
		return cpu;
	}
	
	public int getHdd() {
		return hdd;
	}
	
	public int getRam() {
		return ram;
	}
	
	public String getOperationSystem() {
		return operationSystem;
	}
	
	public int getPrice() {
		return price;
	}
	
	public Date getManufacturingDate() {
		return manufacturingDate;
	}
	
	public boolean getAllInOne() {
		return allInOne;
	}
	
	
	//필드값을 문자열로 합치기해서 반환하는 printInformation()작성
	
	public void printInformation() {
		System.out.println(brand + ", " + productNumber + ", " + productCode + ", " + productName + ", " + cpu + ", " + hdd + ", " + ram + ", " + operationSystem + ", " + price + ", " + manufacturingDate + ", " + allInOne);
	}
	
	
	public String printInformationd() {
		return this.brand + ", "
				+ this.productNumber + ", "
				+ this.productCode + ", "
				+ this.productName + ", "
				+ this.cpu + ", "
				+ this.hdd + ", "
				+ this.ram + ", "
				+ this.operationSystem + ", "
				+ this.price + ", "
				+ this.manufacturingDate + ", "
				+ this.allInOne
				;
	}
	
}

SmartPhone

package com.kh.inherit.part01_inheritTest.beforeProduct.model.vo;

import java.util.Date;

public class SmartPhone {

	private String brand;
	private String productNumber;
	private String productCode;
	private String productName;
	private String cpu;
	private int hdd;
	private int ram;
	private String operationSystem;
	private int price;
	private Date manufacturingDate;
	private String mobileAgency;
	
	
	public SmartPhone() {}
	
	
	public SmartPhone(String brand, String productNumber, String productCode, String productName, String cpu, int hdd, int ram, String operationSystem, int price, Date manufacturingDate, String mobileAgency) {
		this.brand = brand;
		this.productNumber = productNumber;
		this.productCode = productCode;
		this.productName = productName;
		this.cpu = cpu;
		this.hdd = hdd;
		this.ram = ram;
		this.operationSystem = operationSystem;
		this.price = price;
		this.manufacturingDate = manufacturingDate;
		this.mobileAgency = mobileAgency;
	}
	
	public void setBrand(String brand) {
		this.brand = brand;
	}
	
	public void setProductNumber(String productNumber) {
		this.productNumber = productNumber;
	}
	
	public void setProductCode(String productCode) {
		this.productCode = productCode;
	}
	
	public void setProductName(String productName) {
		this.productName = productName;
	}
	
	public void setCpu(String cpu) {
		this.cpu = cpu;
	}
	
	public void setHdd(int hdd) {
		this.hdd = hdd;
	}
	
	public void setRam(int ram) {
		this.ram = ram;
	}
	
	public void setOperationSystem(String operationSystem) {
		this.operationSystem = operationSystem;
	}
	
	public void setPrice(int price) {
		this.price = price;
	}
	
	public void setManufacturingDate(Date manufacturingDate) {
		this.manufacturingDate = manufacturingDate;
	}
	
	public void setMobileAgency(String mobileAgency) {
		this.mobileAgency = mobileAgency;
	}
	
	public String getBrand() {
		return brand;
	}
	
	public String getProductNumber() {
		return productNumber;
	}
	
	public String getProductCode() {
		return productCode;
	}
	
	public String getProductName() {
		return productName;
	}
	
	public String getCpu() {
		return cpu;
	}
	
	public int getHdd() {
		return hdd;
	}
	
	public int getRam() {
		return ram;
	}
	
	public String getOperationSystem() {
		return operationSystem;
	}
	
	public int getPrice() {
		return price;
	}
	
	public Date getManufacturingDate() {
		return manufacturingDate;
	}
	
	public String getMobileAgency() {
		return mobileAgency;
	}
	
	
	
	
	//필드값을 문자열로 합치기해서 반환하는 printInformation()작성
	
	public void printInformation() {
		System.out.println(brand + ", " + productNumber + ", " + productCode + ", " + productName + ", " + cpu + ", " + hdd + ", " + ram + ", " + operationSystem + ", " + price + ", " + manufacturingDate + ", " + mobileAgency);
	}
	
	
	public String printInformation() {
		return this.brand + ", "
				+ this.productNumber + ", "
				+ this.productCode + ", "
				+ this.productName + ", "
				+ this.cpu + ", "
				+ this.hdd + ", "
				+ this.ram + ", "
				+ this.operationSystem + ", "
				+ this.price + ", "
				+ this.manufacturingDate + ", "
				+ this.mobileAgency;
	}
	
}

Television

package com.kh.inherit.part01_inheritTest.beforeProduct.model.vo;

import java.util.Date;

public class Television {

	
	
	private String brand;
	private String productNumber;
	private String productCode;
	private String productName;
	private int price;
	private Date manufacturingDate;
	private int inchType;
	
	public Television() {}
	
	
	//모든 필드를 초기화하는 생성자
	public Television(String brand, String productNumber, String productCode, String productName, int price, Date manufacturingDate, int inchType) {
		this.brand = brand;
		this.productNumber = productNumber;
		this.productCode = productCode;
		this.productName = productName;
		this.price = price;
		this.manufacturingDate = manufacturingDate;
		this.inchType = inchType;
		
	}
	
	//setter & getter
	public void setBrand(String brand) {
		this.brand = brand;
	}
	
	public void setProductNumber(String productNumber) {
		this.productNumber = productNumber;
	}
	
	public void setProductCode(String productCode) {
		this.productCode = productCode;
	}
	
	public void setProductName(String productName) {
		this.productName = productName;
	}
	
	public void setPrice(int price) {
		this.price = price;
	}
	
	public void setManufacturingDate(Date manufacturingDate) {
		this.manufacturingDate = manufacturingDate;
	}
	
	public void setInchType(int inchType) {
		this.inchType = inchType;
	}
	
	public String getBrand() {
		return brand;
	}
	
	public String getProductNumber() {
		return productNumber;
	}
	
	public String getProductCode() {
		return productCode;
	}
	
	public String getProductName() {
		return productName;
	}
	
	public int getPrice() {
		return price;
	}
	
	public Date getManufacturingDate() {
		return manufacturingDate;
	}
	
	public int getInchType() {
		return inchType;
	}
	
	
	//필드값을 문자열로 합치기해서 반환하는 printInformation()작성
	
	public void printInformation() {
		System.out.println(brand + ", " + productNumber + ", " + productCode + ", " + productName + ", " + price + ", " + manufacturingDate + ", " + inchType);
	}
	
	
	public String printInformation() {
		return this.brand + ", "
				+ this.productNumber + ", "
				+ this.productCode + ", "
				+ this.productName + ", "
				+ this.price + ", "
				+ this.inchType;
	}
}
반응형

'Programming > Java' 카테고리의 다른 글

[Java] 기본 API  (0) 2022.03.07
[Java] 다형성  (0) 2022.03.07
[Java] 배열  (0) 2022.03.07
[Java] 반복문  (0) 2022.03.07
[Java] 조건문  (0) 2022.03.07

댓글