Inheritance
상속
; 부모의 필드와 메소드를 가져와서 내것처럼 접근할 수 있다
A 클래스
a = 7
b = 10
a( ){ }
C 클래스 extends A클래스
c( ){ }
-------------------------------
C objC = new C(); objC -----> a : 7
b : 10
a( )
--------
c( )
class A{
int a = 7;
int b = 10;
A(){
System.out.println("난 부모클래스얌-A");
}
void a() {
System.out.println("난 부모메서드얌-A");
}
}
class B {
B(){
System.out.println("난 자식클래스얌-B");
}
void b(){
System.out.println("난 자식메서드얌-B");
}
}
//상속받은 C
class C extends A{
C(){
System.out.println("나도 자식클래스야-C");
}
void c() {
System.out.println("나도 자식메서드야 - C");
}
}
public class Inherit1 {
public static void main(String[] args) {
A objA = new A();
System.out.println(objA.a);
System.out.println(objA.b);
objA.a();
B objB = new B();
objB.b();
System.out.println("*************");
C objC = new C();
objC.c();
//부모것의 필드와 메서드를 호출
System.out.println(objC.a);
System.out.println(objC.b);
objC.a();
}
}
자신 부모
this this() super super()
객체 생성자 객체 생성자
첫줄에 작성되어야 함 첫줄에 작성되어야 함
오버로딩으로 호출함 오버로딩으로 호출함
this.필드 super.필드
this.메소드 super.메소드
package inheritance;
class A3{
int a=5;
int b=7;
A3(){
System.out.println("1. 부모의 기본생성자");
}
void display() {
System.out.println("대박");
}
void print() {
System.out.println("난 부모 메소드얌");
}
}
class B3 extends A3{
int a = 10;
int b = 100;
B3(){
System.out.println("2. 자식의 기본생성자");
}
void print() {
super.display();
super.print();
System.out.println("난 자식 메소드의 a: "+a);
System.out.println("난 부모필드 a: "+super.a);
System.out.println("난 자식메소드 b: "+b);
System.out.println("난 자식필드 b: "+super.b);
}
}
public class inherit3 {
public static void main(String[] args) {
B3 obj = new B3();
obj.print();
obj.display();
}
}
//좌표
class Point{
int x,y;
void set(int x, int y) {
this.x = x;
this.y = y;
}
void showPoint() {
System.out.println("("+x+","+y+")");
}
}
//컬러좌표
class ColorPoint extends Point{
String color;
void setColor(String color) {
this.color = color;
}
void showColorPoint() {
System.out.println("color: "+color);
super.showPoint();
}
}
public class Inherit4 {
public static void main(String[] args) {
ColorPoint cp = new ColorPoint();
cp.set(3, 4);
cp.setColor("red");
cp.showColorPoint();
}
}
업캐스팅, 다운스캐팅
- 업캐스팅 : 서브클래스는 슈퍼클래스의 모든 특성을 상속받는다
서브클래스도 부모클래스로 취급 받을 수 있다
>> 자식이 부모타입으로 변환하는 것을 업캐스팅이라고 한다
>> 업캐스팅이 되면 자식의 것에 접근이 불가하다
- 다운캐스팅:
업캐스팅된 것을 다시 원래 상태로 돌려놓는 것을 다운캐스팅이라고 한다
>> 다운캐스팅은 명시적으로 해야한다
오버라이딩
- 부모의 메소드를 재정의한 것이다
- 부모의 메소드보다 자식의 메소드가 좁으면 오버라이딩이 불가하다
- 부모와 자식의 메소드가 메소드이름, 매개변수, 리턴타입이 모두 같아야 한다
class 동물{
void speak() {
System.out.println("소리를 내고 웁니다.");
}
}
class 강아지 extends 동물{
@Override
void speak() {
System.out.println("귀엽다멍");
}
}
class 고양이 extends 동물{
void speak() {
System.out.println("반갑다냥");
}
}
class 토끼 extends 동물{
void speak() {
System.out.println("깡총깡총");
}
}
public class Inherit6 {
public static void main(String[] args) {
동물 a = new 강아지();
a.speak();
동물 b = new 고양이();
b.speak();
동물 c = new 토끼();
c.speak();
}
}
Shape - draw() 도형을 그립니다
|
-------------------------------------
| | | |
Line Circle Rect Tri
draw() draw() draw() draw()
선을 그립니다 원을 그립니다 사각형을 그립니다 삼각형을 그립니다
class Shape{
Shape(){
}
void draw() {
System.out.println("도형을 그립니다");
}
}
class Line extends Shape{
void draw() {
System.out.println("선을 그립니다");
}
}
class Circle extends Shape{
void draw() {
System.out.println("원을 그립니다");
}
}
class Rect extends Shape{
void draw() {
System.out.println("사각형을 그립니다");
}
}
class Tri extends Shape{
void draw() {
System.out.println("삼각형을 그립니다");
}
}
public class Inherit7 {
}
package inheritance;
import java.util.Scanner;
class Obj{
void cal(int x, int y) {
System.out.println("사칙연산을 시작합니다.");
}
}
class Add extends Obj{
void cal(int x, int y) {
System.out.println("결과: "+(x+y));
}
}
class Substract extends Obj{
void cal(int x, int y) {
System.out.println("결과: "+(x-y));
}
}
class Mul extends Obj{
void cal(int x, int y) {
System.out.println("결과: "+(x*y));
}
}
class Div extends Obj{
void cal(int x, int y) {
System.out.print("결과: "+(x/(float)y)); }
}
public class Inherit8 {
public static void main(String[] args) {
Obj add = new Add();
add.cal(10, 5);
System.out.println("****************");
Scanner sc = new Scanner(System.in);
System.out.println("예시와 같이 입력하시오(예: 3 + 4 >>");
int x = sc.nextInt();
String op = sc.next();
int y = sc.nextInt();
if(op.equals("+")) {
Obj obj = new Add();
obj.cal(x, y);
}else if(op.equals("-")) {
Obj obj = new Substract();
obj.cal(x, y);
}else if(op.equals("*")) {
Obj obj = new Mul();
obj.cal(x, y);
}else if(op.equals("/")) {
Obj obj = new Div();
obj.cal(x, y);
}else {
System.out.println("잘못 입력하셨습니다.");
}
sc.close();
}
//배열에 넣고 활용해본다.
// obj ----------> [더하기] [빼기] [곱하기] [나누기]
}
package inheritance;
class Car{
int speed=100;
void move() {
System.out.println("이동한다");
}
}
class Bus{
int speed=60;
void move() {
System.out.println("사람을 많이 태우고 이동한다.");
}
}
class Ambulance{
int speed=200;
void move() {
System.out.println("싸이렌을 울리며 이동한다.");
}
void special() {
System.out.println("환자를 태우고 있다");
}
}
class FireEngine{
int speed =150;
void move() {
System.out.println("물을 뿌리며 이동한다");
}
}
public class Inherit9 {
public static void main(String[] args) {
//car---> [버스] [앰뷸런스][소방차]
//전체 출력해보세요
Car[] car = new Car[3];
car[0] = new Bus();
car[1]=new Ambulance();
car[2]=new FireEngine();
//전체출력해보세요
for(Car c: car) {
//System.out.println(c.speed);
c.move();
}
Ambulance am = (Ambulance)car[1];
}
}