국비 19일차 상속, 오버라이드
2021. 1. 29. 19:53
2021.01.29 국비교육 19일차
[TOC]
IS A 관계
- 같은 종의 비슷한 속성 및 동작을 가진 객체들 간의 관계
package com.test;
class Employee{
String name;
int salary;
public Employee() {}
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
class Manager extends Employee{
String depart;
public String getManager() {
return name + "\t" + salary + "\t" + depart;
}
//public Manager() {}
public Manager(String name, int salary, String depart) {
super(); // 부모의 기본생성자 호출
this.name = name;
this.salary = salary;
this.depart = depart;
}
}
public class Ex06_1 {
public static void main(String[] args) {
Employee emp = new Employee("홍길동", 2000);
Manager man = new Manager("이순신", 400, "개발");
}
}
상속[inheritance]
-
반드시 객체간에 IS A 관계가 성립되어야 한다.
-
생성자와 private로 지정된 멤버는 상속이 안된다.
-
extends 키워드를 사용하여 상속관계 표시
-
생성자는 상속되지 않음
-
모든 클래스는 부모객체를 먼저 생성한 후 자신이 생성
-
부모생성자를 호출하기 위해서 super() 사용
package com.test3;
class Employee{
String name;
int salary;
public String getEmployee(){
System.out.println("employee getEmployee 출력");
return name + "\t" + salary;
}
public Employee() {}
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
class Engineer extends Employee{
int bonus;
public Engineer(String name, int salary, int bonus) {
super(name, salary);
this.bonus = bonus;
}
@Override
public String getEmployee(){
System.out.println("Engineer getEmployee 출력");
return super.getEmployee() + "\t" + bonus;
}
}
class Manager extends Employee{
String depart;
@Override
public String getEmployee() {
System.out.println("manager getemployee 출력");
return super.getEmployee() + "\t" + depart;
}
public Manager() {}
public Manager(String name, int salary, String depart) {
super(name, salary);
this.depart = depart;
}
}
public class Ex06_6 {
public static void main(String[] args) {
}
}
'ETC > 국비교육' 카테고리의 다른 글
국비 21일차 JAVA(중첩, Comparator, DecimalFormat, 문자열 나누기, StringTokenizer, StringBuffer, Wrapper(오토박싱, 언박싱), Random, Calander, SimpledataFormat, Array API, ENUM, 예외(try-catch, finally)) (0) | 2021.02.02 |
---|---|
국비 20일차 다형성, 추상함수, 인터페이스 (0) | 2021.02.01 |
국비 18일차 JAVA 초기화블록, 싱글톤, final, vargars (0) | 2021.01.28 |
국비 17일차 static (0) | 2021.01.27 |
국비 16일차 JAVA(생성자, 객체 생성, 오버로딩, this, getter/setter) (0) | 2021.01.26 |