PowerPoint Presentation

Similar documents
gnu-lee-oop-kor-lec06-3-chap7

쉽게 풀어쓴 C 프로그래밍

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밍

Microsoft PowerPoint - java1-lecture5.ppt [호환 모드]

JAVA PROGRAMMING 실습 08.다형성

PowerPoint Presentation

PowerPoint Presentation

Microsoft PowerPoint - java1-lecture5.ppt [호환 모드]

Microsoft PowerPoint - 2강

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

5장.key

PowerPoint Presentation

예제 2) Test.java class A intvar= 10; void method() class B extends A intvar= 20; 1"); void method() 2"); void method1() public class Test 3"); args) A

PowerPoint Presentation

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

쉽게 풀어쓴 C 프로그래밍

PowerPoint Presentation

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밍

PowerPoint Presentation

Design Issues

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

No Slide Title

쉽게 풀어쓴 C 프로그래밍

JAVA PROGRAMMING 실습 02. 표준 입출력

쉽게 풀어쓴 C 프로그래밍

(8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI= ; // PI 이름으로 로초기화된정적상수 public

JAVA PROGRAMMING 실습 07. 상속

(Microsoft PowerPoint - java2-lecture3.ppt [\310\243\310\257 \270\360\265\345])

PowerPoint Presentation

JAVA PROGRAMMING 실습 05. 객체의 활용

PowerPoint 프레젠테이션

PowerPoint Presentation

PowerPoint Presentation

Microsoft PowerPoint - additional08.ppt [호환 모드]

10.0pt1height.7depth.3width±â10.0pt1height.7depth.3widthÃÊ10.0pt1height.7depth.3widthÅë10.0pt1height.7depth.3width°è10.0pt1height.7depth.3widthÇÁ10.0pt1height.7depth.3width·Î10.0pt1height.7depth.3width±×10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width¹Ö pt1height.7depth.3widthŬ10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width½º, 10.0pt1height.7depth.3width°´10.0pt1height.7depth.3widthü, 10.0pt1height.7depth.3widthº¯10.0pt1height.7depth.3width¼ö, 10.0pt1height.7depth.3width¸Þ10.0pt1height.7depth.3width¼Ò10.0pt1height.7depth.3widthµå

Microsoft PowerPoint - Lect04.pptx

Microsoft PowerPoint - chap11

PowerPoint Presentation

Microsoft PowerPoint - java2 [호환 모드]

슬라이드 1

자바 프로그래밍

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

쉽게

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

C++ Programming

Microsoft Word - java19-1-midterm-answer.doc

PowerPoint Presentation

비긴쿡-자바 00앞부속

PowerPoint Presentation

PowerPoint 프레젠테이션

슬라이드 1

제11장 프로세스와 쓰레드

JAVA PROGRAMMING 실습 05. 객체의 활용

PowerPoint Presentation

01-OOPConcepts(2).PDF

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

Chapter 6 Objects and Classes

PowerPoint Template

17장 클래스와 메소드

Slide 1

Java ~ Java program: main() class class» public static void main(string args[])» First.java (main class ) /* The first simple program */ public class

Network Programming

1. 객체의생성과대입 int 형변수 : 선언과동시에초기화하는방법 (C++) int a = 3; int a(3); // 기본타입역시클래스와같이처리가능 객체의생성 ( 복습 ) class CPoint private : int x, y; public : CPoint(int a

Microsoft PowerPoint - Java7.pptx

Microsoft PowerPoint - 5장

PowerPoint Presentation

PowerPoint Template

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345])

09-interface.key

05-class.key

교육자료

Microsoft PowerPoint - lec12 [호환 모드]

Slide 1

<4D F736F F F696E74202D205B4A415641C7C1B7CEB1D7B7A1B9D65D35C0E5BBF3BCD3B0FAB4D9C7FCBCBA>

Microsoft PowerPoint - C++ 5 .pptx

Microsoft Word - java18-1-final-answer.doc

A Tour of Java IV

Modern Javascript

PowerPoint Presentation

C++ Programming

<4D F736F F F696E74202D2036C0CFC2B05FB0B4C3BCC1F6C7E2C7C1B7CEB1D7B7A1B9D62E707074>

class Sale void makelineitem(productspecification* spec, int qty) SalesLineItem* sl = new SalesLineItem(spec, qty); ; 2. 아래의액티비티다이어그램을보고 Java 또는 C ++,

슬라이드 1

Microsoft Word - EEL2 Lab4.docx

PowerPoint Presentation

1

JAVA PROGRAMMING 실습 09. 예외처리

Microsoft Word - java19-1-final-answer.doc

JVM 메모리구조

No Slide Title

(Microsoft PowerPoint - 07\300\345.ppt [\310\243\310\257 \270\360\265\345])

PowerPoint 프레젠테이션

Microsoft PowerPoint - lec7_package [호환 모드]

Spring Boot/JDBC JdbcTemplate/CRUD 예제

PowerPoint Presentation

1. 상속의기본개념 다음과같은문제를위한클래스설계 자동차 속성 : 색상, 배기량, 현재속도 메서드 : 가속하라, 멈춰라, 시동을켜라 트럭 속성 : 색상, 배기량, 현재속도, 최대중량 메서드 : 가속하라, 멈춰라, 시동을켜라 택시 속성 : 색상, 배기량, 현재속도, 요금,

Transcription:

객체지향프로그래밍 상속 손시운 ssw5176@kangwon.ac.kr

상속이란? 상속의개념은현실세계에도존재한다. 2

상속의장점 상속의장점 상속을통하여기존클래스의필드와메소드를재사용 기존클래스의일부변경도가능 상속을이용하게되면복잡한 GUI 프로그램을순식간에작성 상속은이미작성된검증된소프트웨어를재사용 신뢰성있는소프트웨어를손쉽게개발, 유지보수 코드의중복을줄일수있다. 3

상속 4

부모클래스와자식클래스 부모클래스는추상적이고자식클래스는구체적이다. 5

상속의형식 6

상속예제 : 자동차 7

자식클래스는부모클래스를포함 8

상속받은필드와메소드사용 멤버연산자 (.) 를사용한다. 9

상속이필요한이유 코드를재사용할수있다. 중복을줄일수있다. 10

상속이중복을줄이는이유 11

LAB: 동물예제 12

SOLUTION: 동물예제 13

LAB: 도형예제 x와 y는도형의좌측상단좌표이다. width와 height는사각형의가로길이와세로길이이다. print() 에서는도형의위치를화면에출력한다. draw() 에서는사각형의위치와크기를화면에출력한다. area() 에서는사각형의면적을계산하여반환한다. 14

SOLUTION: 도형예제 15

SOLUTION: 도형예제 16

SOLUTION: 도형예제 17

상속과접근제어 18

접근제어지정자 19

예제 public class Shape { private int x; private int y; void print() { System.out.println("x 좌표 : " + x + " y 좌표 : " + y); 20

부모클래스의 private 멤버접근 public class Rectangle extends Shape { private int width; private int height; double calcarea() { return width * height; void draw() { System.out.println("(" + x + "," + y + ") 위치에 " + " 가로 : " + width + " 세로 : " + height); 부모클래스의 private 멤버 x 와 y 는사용할수없다. 21

LAB: 직원과매니저클래스 직원 (Employee) 과매니저 (Manager) 의예 22

SOLUTION 23

SOLUTION 24

SOLUTION 25

SOLUTION 26

메소드오버라이딩 메소드오버라이딩 (method overriding): 자식클래스가필요에따라상속된 메소드를다시정의하는것 27

메소드재정의의예 class Animal { public void sound() { class Dog extends Animal { public void sound() { System.out.println(" 멍멍!"); public class DogTest { public static void main(string[] args) { Dog d = new Dog(); d.sound(); 멍멍! 28

메소드를오버라이딩하려면 메소드의이름, 반환형, 매개변수의개수와데이터타입이일치하여야한다. public class Animal { public void sound() { public class Dog extends Animal { public int sound() { 오버라이딩이아님! 29

어노테이션 public class Animal { public void sound() { class Dog extends Animal { @Override void saund() { // 오류발생! System.out.println(" 멍멍!"); 오버라이딩이아님 1부터 The method 10까지의saund() 정수의of 합 type = 55Dog must override or implement a supertype method 30

키워드 super 를사용하여부모클래스멤버접근 31

LAB: 은행클래스작성하기 32

SOLUTION 33

SOLUTION 34

상속과생성자 서브클래스의객체가생성될때, 서브클래스의생성자만호출될까? 아니면 수퍼클래스의생성자도호출되는가? class Base{ public Base() { System.out.println("Base() 생성자 "); ; class Derived extends Base { public Derived() { System.out.println("Derived() 생성자 "); ; public class Test { public static void main(string[] args) { Derived r = new Derived(); ; 35

실행출력 생성자의호출순서는 ( 부모클래스의생성자 ) -> ( 자식클래스의생성자 ) 순 으로된다. 36

명시적인생성자호출 super 를이용하여서명시적으로수퍼클래스의생성자호출 class Shape { public Shape(String msg) { System.out.println("Shape 생성자 () " + msg); ; public class Rectangle extends Shape { public Rectangle(){ super("from Rectangle"); // 명시적인호출 System.out.println("Rectangle 생성자 ()"); ; 37

묵시적인생성자호출에러 class Shape { public Shape(String msg) { System.out.println("Shape 생성자 ()"); ; class Rectangle extends Shape { public Rectangle() { ; System.out.println("Rectangle 생성자 ()"); 1Implicit 부터 10까지의 super 정수의 constructor 합 = 55 Shape() is undefined. 38

LAB: 복잡한상속계층구조만들어보기 예를들어서 Shape이 Rectangle의부모클래스이고다시 Rectangle이 ColoredRectangle의부모클래스가될수있는것이다. 이런경우의 ColoredRectangle은 Shape와 Rectangle의모든멤버를상속받게된다. 39

SOLUTION public class Shape { private int x; private int y; public Shape(int x, int y) { System.out.println("Shape()"); this.x = x; this.y = y; 40

SOLUTION public class Rectangle extends Shape { private int width; private int height; public Rectangle(int x, int y, int width, int height) { super(x, y); System.out.println("Rectangle()"); this.width = width; this.height = height; double calcarea() { return width * height; 41

SOLUTION public class ColoredRectangle extends Rectangle { String color; public ColoredRectangle(int x, int y, int width, int height, String color) { super(x, y, width, height); System.out.println("ColoredRectangle()"); this.color = color; public static void main(string[] args) { ColoredRectangle obj = new ColoredRectangle(10, 10, 20, 20, "red"); 42

추상클래스 추상클래스 (abstract class): 몸체가구현되지않은메소드를가지고있는클 래스 추상클래스는추상적인개념을표현하는데적당하다. 43

추상클래스의정의 public abstract class Animal { public abstract void move();... 추상메소드정의 44

추상메소드의예 45

추상클래스 abstract class Shape { private int x, y; public void move(int x, int y) this.x = x; this.y = y; public abstract void draw(); class Rectangle extends Shape { private int width, height; public void draw() { // 추상메소드구현 System.out.println(" 사각형그리기메소드 "); class Circle extends Shape { private int radius; public void draw() { System.out.println(" 원그리기메소드 "); 46

다형성이란? 다형성 (polymorphism) 이란객체들의타입이다르면똑같은메시지가전달 되더라도서로다른동작을하는것 47

자바에서의자료형검사 클래스 A 의참조변수로클래스 B 의객체를참조할수는없다. class A { A() { class B { B() { public class TypeTest1 { public static void main(string args[]) { A a = new B(); // NO! 48

상향형변환 부모클래스의참조변수는자식클래스의객체를참조할수있다! class A { A() { class B extends A { B() { public class TypeTest1 { public static void main(string args[]) { A a = new B(); // OK! 49

상속과다형성 하나의예로 Rectangle, Triangle, Circle 등의도형클래스가부모클래스인 Shape 클래스로부터상속되었다고가정하자. 50

상향형변환 class Shape { protected int x, y; class Rectangle extends Shape { public int width, height; class Triangle extends Shape { public int base, height; class Circle extends Shape { public int radius; 51

상향형변환 public class ShapeTest { public static void main(string args[]) { Shape s1, s2; s1 = new Shape(); // 1 당연하다. s2 = new Rectangle(); // 2 Rectangle 객체를 Shape 변수로 // 가리킬수있을까? 52

왜그럴까? 서브클래스객체는수퍼클래스객체를포함하고있기때문이다. 53

예제.. public class ShapeTest { public static void main(string args[]) { Shape s = new Rectangle(); Rectangle r = new Rectangle(); s.x = 0; s.y = 0; s.width = 100; s.height = 100; width cannot be resolved or is not a field 1height 부터 10cannot 까지의be 정수의 resolved 합 = or 55is not a field 컴파일오류가발생한다. s 를통해서는 Rectangle 클래스의필드와메소드에접근할수없다. 54

다형성 55

형변환 Shape s = new Rectangle(); s 를통하여 Rectangle 클래스의필드와메소드를사용하고자할때는어떻 게하여야하는가? ((Rectangle) s).setwidth(100); 56

하향형변환 서브클래스참조변수로수퍼클래스객체를참조하는것으로일반적인상 황에서는컴파일오류이다. Rectangle r; r = new Shape(); // NOT OK! 만약서브클래스객체인데형변환에의하여일시적으로수퍼클래스참조변수에의하여참조되고있는경우는가능 Rectangle r; Shape s; s = new Rectangle(); r = (Rectangle)s; r.width = 100; r.height = 100; 57

동적메소드호출 다형성은객체들이동일한메시지를받더라도각객체의타입에따라서서 로다른동작을하는것 58

동적메소드호출 class Shape { protected int x, y; public void draw() { System.out.println("Shape Draw"); class Rectangle extends Shape { private int width, height; public void draw() { System.out.println("Rectangle Draw"); 59

동적메소드호출 class Triangle extends Shape { private int base, height; public void draw() { System.out.println("Triangle Draw"); class Circle extends Shape { private int radius; public void draw() { System.out.println("Circle Draw"); 60

동적메소드호출 public class ShapeTest { public static void main(string arg[]) { Shape s1, s2, s3, s4; s1 = new Shape(); s2 = new Rectangle(); s3 = new Triangle(); s4 = new Circle(); s1.draw(); s2.draw(); s3.draw(); s4.draw(); 61

실행결과 Shape Draw Rectangle Draw Triangle Draw Circle Draw 62

동적바인딩 메소드호출을실제메소드의몸체와연결하는것을바인딩 (binding) 이라고한다. 자바가상머신 (JVM) 은실행단계에서객체의타입을보고적절한메소드를호출하게된다. 이것을동적바인딩 (dynamic binding) 또는가상메소드호출 (virtual method invocation) 이라고한다. 63

예제 public class ShapeTest { private static Shape arrayofshapes[]; public static void main(string arg[]) { init(); drawall(); public static void init() { arrayofshapes = new Shape[3]; arrayofshapes[0] = new Rectangle(); arrayofshapes[1] = new Triangle(); arrayofshapes[2] = new Circle(); public static void drawall() { for (int i = 0; i < arrayofshapes.length; i++) { arrayofshapes[i].draw(); 64

예제 Rectangle Draw Triangle Draw Circle Draw 65

어떤장점이있을까? 새로운클래스가추가되더라도다른코드는변경할필요가없다. class Cylinder extends Shape { private int radius, height; public void draw(){ System.out.println("Cylinder Draw"); 66

메소드의매개변수 메소드의매개변수로부모클래스참조변수를이용한다. 다형성을이용하는전형적인방법 67

예제 public class ShapeTest { public static void printlocation(shape s) { System.out.println("x=" + s.x + " y=" + s.y); public static void main(string arg[]) { Rectangle s1 = new Rectangle(); Triangle s2 = new Triangle(); Circle s3 = new Circle(); printlocation(s1); printlocation(s2); printlocation(s3); 68

LAB: 동적메소드호출 강아지와고양이를나타내는클래스를작성하자. 이들클래스의부모클래 스로 Animal 클래스를정의한다. 강아지와고양이클래스의 sound() 메소드 를호출하면각동물들의소리가출력되도록프로그램을작성해보자. Animal 클래스의 sound() 멍멍야옹 69

SOLUTION class Animal { void sound() { System.out.println("Animal 클래스의 sound()"); class Dog extends Animal { void sound() { System.out.println(" 멍멍 "); class Cat extends Animal { void sound() { System.out.println(" 야옹 "); 70

SOLUTION public class DynamicCallTest { public static void main(string args[]) { Animal animal = new Animal(); Dog dog = new Dog(); Cat cat = new Cat(); Animal obj; obj = animal; obj.sound(); obj = dog; obj.sound(); obj = cat; obj.sound(); 71

Object 클래스 Object 클래스는 java.lang 패키지에들어있으며자바클래스계층구조에 서맨위에위치하는클래스 72

Object 의메소드 73

getclass() class Car {... public class CarTest { public static void main(string[] args) { Car obj = new Car(); System.out.println("obj is of type " + obj.getclass().getname()); obj is of type Car obj is of type Car 74

equals() 메소드 Object 에서제공되는 equals() 는 == 연산자를사용하여서객체의주소가동 일한지를검사하여서 true 또는 false 를반환한다. 하지만객체에대해서는 이것이올바르지않는경우가많이있다. 75

equals() 메소드 class Car { private String model; public Car(String model) { this.model= model; public boolean equals(object obj) { if (obj instanceof Car) return model.equals(((car) obj).model); else return false; public class CarTest { public static void main(string[] args) { Car firstcar = new Car("HMW520"); Car secondcar = new Car("HMW520"); Object 의 equals() 를재정의 if (firstcar.equals(secondcar)) { System.out.println(" 동일한종류의자동차입니다."); else { System.out.println(" 동일한종류의자동차가아닙니다."); 동일한 1부터 10종류의까지의자동차입니다정수의합 = 55. 76

객체의실제타입 Shape s = getshape(); if (s instanceof Rectangle) { System.out.println("Rectangle 이생성되었습니다 "); else { System.out.println("Rectangle 이아닌다른객체가생성되었습니다 "); 77

hashcode() 메소드 hashcode() 는해싱이라는탐색알고리즘에서필요한해시값을생성하는메 소드이다. 78

tostring() Object 클래스의 tostring() 메소드는객체의문자열표현을반환 public class Car { private String model; public Car(String model) { this.model = model; public String tostring() { return 모델 : + model; Object 의 tostring() 를재정의 79

IS-A 관계 is-a 관계 : ~ 은 ~ 이다 와같은관계 상속은 is-a 관계이다. 자동차는탈것이다 (Car is a Vehicle). 강아지는동물이다 (Dog is a Animal). 80

HAS-A 관계 has-a 관계 : ~ 은 ~ 을가지고있다 와같은관계 도서관은책을가지고있다 (Library has a book). 거실은소파를가지고있다 (Living room has a sofa). 81

HAS-A 관계 객체지향프로그래밍에서 has-a 관계는구성관계 (composition) 또는집합 관계 (aggregation) 를나타낸다. 82

HAS-A 관계의구현 class Vehicle { class Carburetor { public class Car extends Vehicle { private Carburetor cb; 83

HAS-A 관계의예제 84

HAS-A 관계의예제 public class Date { private int year; private int month; private int date; public Date(int year, int month, int date) { this.year = year; this.month = month; this.date = date; @Override public String tostring() { return "Date [year=" + year + ", month=" + month + ", date=" + date + "]"; 85

HAS-A 관계의예제 public class Employee { private String name; private Date birthdate; public Employee(String name, Date birthdate) { this.name = name; this.birthdate = birthdate; @Override public String tostring() { return "Employee [name=" + name + ", birthdate=" + birthdate + "]"; 86

HAS-A 관계의예제 public class EmployeeTest { public static void main(string[] args) { Date birth = new Date(1990, 1, 1); Employee employee = new Employee(" 홍길동 ", birth); System.out.println(employee); Employee [name= 홍길동, birthdate=date [year=1990, month=1, date=1]] 87

종단클래스 종단클래스 (final class) 는상속을시킬수없는클래스를말한다. 종단클래스가필요한이유는주로보안상의이유때문이다. public final class MyFinal {... public class ThisIsWrong extends MyFinal {... 88

종단메소드 특정한메소드만오버라이드될수없게만들려면종단메소드 (final method) 로선언 class Baduk { enum BadukPlayer { WHITE, BLACK... final BadukPlayer getfirstplayer() { return BadukPlayer.BLACK; 89

정적메소드오버라이딩 부모클래스의메소드중에서정적메소드를재정의 ( 오버라이드 ) 하면부모클래스객체에서호출되느냐아니면자식클래스에서호출되느냐에따라서호출되는메소드가달라진다. public class Animal { public static void eat() { System.out.println("Animal의정적메소드 eat()"); public void sound() { System.out.println("Animal의인스턴스메소드 sound()"); 90

정적메소드오버라이딩 public class Cat extends Animal { public static void eat() { System.out.println("Cat의정적메소드 eat()"); public void sound() { System.out.println("Cat의인스턴스메소드 sound()"); public static void main(string[] args) { Cat mycat = new Cat(); Animal myanimal = mycat; Animal.eat(); myanimal.sound(); 91

실행결과 Animal 의정적메소드 eat() Cat 의인스턴스메소드 sound() 92