/ JAVA

객체지향 프로그래밍 복습 (6) Inheritance and Polymorphism

[JAVA] 객체지향 프로그래밍 복습 (6) Inheritance and Polymorphism

자바

자바(Java)는 C언어에 객체 지향적 기능을 추가하여 만든 C++과는 달리, 처음부터 객체 지향 언어로 개발된 프로그래밍 언어입니다. 자바는 자바 가상 머신(JVM, Java Virtual Machine)을 사용하여, 운영체제와는 독립적으로 동작할 수 있습니다. 따라서 자바는 어느 운영체제에서나 같은 형태로 실행될 수 있습니다. 바로 이러한 점이 수많은 개발자로 하여금 자바를 사용하게 하는 원동력이 되고 있습니다. 현재 자바는 전 세계에서 가장 많이 사용하는 프로그래밍 언어 중 하나입니다.

상속 Inheritance

  • 상위 클래스의 모든 멤버를 하위 클래스가 물려 받는 것.
  • 재사용성과 코드의 간결성 향상
  • 자신이 만들어서 상속 시킬수도 있고 JDK가 지원하는 클래스로 부터 상속 받아 사용가능
  • 최상위 클래스는 java.lang.Object
  • 상속 키워드 : extends
  • 상속의 종류 : 단일 상속, 다중 상속
  • super : 상위 클래스 객체 지정

다형성 Polymorphism

  • 클래스 이름 앞에 abstract라는 예약어가 사용된 클래스
  • 하위 클래스에서 구현될 기능을 추상 메소드로 선언한 클래스
  • 추상 메소드는 선언만 되어 있고 구현 부분이 없는 메소드로 메서드의 결과형 앞에 abstract를 기재해서 생성
  • 추상 메소드는 반드시 하위 클래스에서 오버라이딩 되어서 구현되어야 한다.
  • 추상 메소드는 일반적인 멤버 변수와 메소드를 가질 수 있습니다.
  • 하지만 객체를 생성하지 못하여 상속을 통해서만 사용되어 집니다.

Person 클래스

상속과 다형성을 복습하기 위해 Person 클래스를 작성합니다. Person 클래스는 멤버 변수로 랜덤의 ID, 이름, 전화번호를 갖습니다. 사람의 정보는 static ArrayList 클래스에 저장합니다. 기능으로는 사람 정보 출력, 배열에 사람 추가, 삭제, 사람 정보 출력이 있습니다.

이 Person 클래스를 상속받는 클래스로는 Customer 클래스와 Staff 클래스가 있습니다.

  • Customer클래스
    • 부모 클래스의 이름과 전화번호를 설정하고 랜덤 고객 ID, 운전면허를 저장합니다.
    • 기능으로는 부모 클래스를 오버라이드 하여 정보 출력과 삭제 기능을 구현합니다.
  • Staff 클래스
    • 부모 클래스의 이름과 전화번호를 설정하고 랜덤 스태프 ID, 근무 부서, 근무 시작 날짜를 저장합니다.
    • 기능으로는 부모 클래스를 오버라이드 하여 정보 출력과 삭제 기능을 구현합니다.

Person.java

package LAB06;

import java.util.ArrayList;
import java.util.Random;

public class Person {
	private int personID;
	private String name;
	private String phone;
	private static ArrayList<Person> persons = new ArrayList<>();

	//Person 생성 구조체
	public Person(String n, String p) {
		Random random = new Random();
		this.personID = random.nextInt(9000) + 1000;
		this.name = n;
		this.phone = p;

		Person.addPerson(this);
	}

	//사람 정보 출력
	public void printInfo() {
		System.out.println("ID: " + this.personID);
		System.out.println("Name: " + this.name);
		System.out.println("Phone: " + this.phone);
	}

	//배열에 사람 추가
	protected static void addPerson(Person p) {
		persons.add(p);
	}

	//배열에서 사람 삭제(삭제시 true, 삭제불가시 false 리턴)
	protected static Boolean deletePerson(Person p) {
		for(Person aPersons : Person.persons) {
			if(aPersons == p) {
				persons.remove(p);
				return true;
			}
		}
		return false;
	}

	//사람의 모든 정보 출력
	public static void printAllPersons() {
		for (Person aPerson : Person.persons) {
			aPerson.printInfo();
			System.out.println();
		}
	}
}

Customer.java

package LAB06;

import java.util.ArrayList;
import java.util.Random;

public class Customer extends Person{
	private int customerID;
	private String driverLicense;
	public static ArrayList<Customer> customers = new ArrayList<>();
	
	public Customer(String n, String p, String license) {
		super(n, p);				//부모 클래스의 name과 phone 설정
		Random random = new Random();
		this.customerID = random.nextInt(9000) + 1000;
		this.driverLicense = license;
		
		customers.add(this);
	}

	//부모 클래스의 printInfo 오버라이드
	@Override
	public void printInfo() {
		System.out.println("=====Customer=====");
		super.printInfo();
		System.out.println("Customer ID: " + this.customerID);
		System.out.println("Driver License: " + this.driverLicense);
		System.out.println();
	}
	
	//finalize 오버라이드로 사람 인스턴스 삭제 기능 추가
	@Override
	protected void finalize() {
		Customer.customers.remove(this);
		System.out.println(super.deletePerson(this));
	}
}

Staff. java

package LAB06;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Random;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Staff extends Person {
	private int staffID;			//스태프 ID
	private String dept;			//근무부서
	private Date dateHired;			//근무 시작 날짜
	public static ArrayList<Staff> staffs = new ArrayList<>();
	
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
	public Staff(String n, String p, String d) throws ParseException {
		super(n, p);			//부모 클래스의 name과 phone 설정
		Random random = new Random();
		this.staffID = random.nextInt(9000) + 1000;
		this.dept = d;
		this.dateHired = dateFormat.parse("2021-04-14");
	}

	//부모 클래스의 printInfo 오버라이드
	@Override
	public void printInfo() {
		System.out.println("=====Staff=====");
		super.printInfo();
		System.out.println("Staff ID: " + this.staffID);
		System.out.println("Department: " + this.dept);
		System.out.println("근무 시작일: " + dateFormat.format(this.dateHired));
	}
	
	//finalize 오버라이드로 사람 인스턴스 삭제 기능 추가
	@Override
	protected void finalize() {
		Staff.staffs.remove(this);
		System.out.println(super.deletePerson(this));
	}		
}

testProgram.java

//20201881 소프트웨어학부 장환곤
//LAB06

package LAB06;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

public class testProgram {

	public static void main(String[] args) throws ParseException {
		//Customer 객체 3개 생성
		Customer c1 = new Customer("Gon", "010-1234-5678", "LDU3495FJVJ1");
		Customer c2 = new Customer("James", "010-2341-5678", "LDU3495FJVJ2");
		Customer c3 = new Customer("Jay", "010-3412-5678", "LDU3495FJVJ3");
		
		//Staff 객체 2개 생성
		Staff s1 = new Staff("Steve", "010-5678-5678", "개발팀");
		Staff s2 = new Staff("John", "010-6789-5678", "홍보팀");
		
		//출력
		Person.printAllPersons();
		
		//c1과 s1 인스턴스 삭제
		System.out.println("인스턴스 삭제");
		System.gc();
		c1.finalize();
		s1.finalize();
		
		//출력
		Person.printAllPersons();
	}
}

결과