Engineering
2015.08.05 22:43

extends, interface, implements 의 정의

조회 수 14264 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

A class implements an interface.
An interface is an abstract class that only contains method signatures and constant declarations. An interface doesn't contain method definitions and can't be instantiated.

A class extends another class.
The new class inherits all of the members of the base class, except those defined with "private" access modifier. New methods can be added without altering the base class, and methods can be overridden without altering the base class.

These concepts exist in many Object Oriented languages.

An example (simple... maybe not the sort of thing you'd do in the real world, but demonstrates the concept)

Lets make a data store interface (

1
2
3
4
5
interface DataStore
{
    void SetValue(string key, string value);
    string GetValue(string key);
}


This interface includes two methods, a set and a get. Now lets use this interface!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class FileDataStore implements DataStore
{
    public void SetValue(string key, string value)
    {
        //Store the key/value pair in the file
    }
    public string GetValue(string key)
    {
        //Retrieve the value for the key from the file
    }
}


This FileDataStore class would work with a file. Lets say you change your mind later and you think you need a database instead to store your information. All you need to do is make a new class that implements your DataStore interface.

Now lets tackle an example of 'extends' We'll start with our base class

1
2
3
4
5
public class Person
{
    public string FirstName;
    public string LastName;
}


This person object has everything we need to know about any person.

1
2
3
4
public class Employee extends Person
{
    public string JobTitle;
}


Our employee object contains the same members as our Person Object (no point in duplicating code, right?) but it also has their job title.
You could pass an employee object to any piece of code that handles a person object.


#출처: http://www.quora.com/What-is-the-difference-between-implements-and-extends


class A extends B 라고 하면
A는 B라는 클래스를 상속 받아서 +a 시키겠다는 뜻이구요
class A implements C 라고 하면
A는 C라는 인터페이스를 구현하겠다~ 라는 뜻입니다.

한마디로, 클래스를 상속받느냐... ?

인터페이스를 구현하느냐...? 의 차이입니다.

 

 

▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧▧

 

 

우선, extends는 일반 클래스와 abstract클래스 상속에 사용되고, implement는 interface상속에 사용됩니다.

그럼, 상속이라는것은? 나의 부모가 부자라면, 내가 부모로부터 상속 받는 다면 나도 부자가 됩니다. 결국, 다른것으로부터 그들의 기능을 빌려다 쓴다고 생각하시면 됩니다. 자바에서의 상속은 2가지 형태가 있습니다.
하나는 extends 이고, 다른 하나는 implements인데, 첫번째는 순수 상속으로 앞에 설명 드린것처럼, 부모로부터 모든 권한과 재산과 능력을 가져 옵니다. 다른 하나는 구현상속, 이라고 합니다. 구현상속 ==> 인터페이스라고 흔히 하죠. 상속이라기 보단. 인터페이스만을 얻어 오는 겁니다. 쉽게 얘기해서, 무언가로 부터 상속은 받되, 그 상속 내용이 란게 비어 있고, 그 비어 있는 것을 내가 꼭 채워서 써야 하는 것을 의미합니다. [소스2]는 childclass2 가 TestInterface을 상속받아서 implement 했다고 생각하시면 됩니다.

다른 비유로 설명한다면, implement(구현 상속)은 조언자로 부터 조언자가 잡은 고기를 얻는게 아니라, 고기를 잡는 방법을 얻어 온다고 생각하시면 됩니다.

그럼 실례로 들어서 생각해 봅시다. 누군가가 나에게 사용자가 입력한 내용을 파일로 저장하는 모듈을 만들어 달라고 했습니다. 파일 저장형식은 1) 엑셀, 2)html, 3)텍스트 세가지의 형식으로 저장 가능하도록 해야 한다고 할때, 개발자는 3가지의 기능이 각기 서로 상이 하므로 서로다른 3개의 모듈을 만들것 입니다. 하지만, 이 모듈을 정작 사용하는 입장에서는 3개의 모듈이 모두 같은 인터페이스를 제공 해주길 바랄것입니다. 결국 자바 클래스관점에서 본다면, 서로 다른 모듈이 하나의 인터페이스로 부터 구현 상속을 받아 야 할것 입니다. 그러면, 사용자는 그 하나의 인터페이스만 보고, 코딩을 하면 될테니까요.

더 쉽게 설명 드리면,
extends: 부모로 부터 상속, implements: 조언자로 부터 상속이라고 보시면 됩니다.

세상의 모든 자식들은 하나의 부모만을 가집니다. 결국, extends을 사용해서, 차일드는 단하나의 부모로 부터 상속 받을 수 있다는거죠. 그럼, 조언자는요? 세상을 살아가는 데 여러 조언자를 만날수 있습니다. 그들은 고기 잡는 법만 알려주죠. 그들이 조언한 방식을 내나름대로 실천하는 게 바로 구현상속(implements)가 되는거죠. 결국, implements을 사용해서, 차일드는 여러 조언자를 만날수 있습니다. 그리고, 조언자는 차일드 윈도우에게 뭔가를 주는 입장이 아니므로, 모두들 interface클래스 이어야 합니다. 즉 방법만 있고, 내용이 없는 거죠.



[소스1]
public interface TestInterface {
public static int num = 8;
public void func1();
public void func2();
}
public class Test {
public void func2() {
System.out.println("func2");
}
}

[소스2]
class childclass1 extends Test{

public void func1() {
System.out.println("fun1.");
}

}

class childclass2 implements TestInterface {
public void func1() {
System.out.println("Class Test1");
}
public void func2() {
System.out.println("Class Test2");
}
}



# 출처: http://gdthink.blogspot.kr/2006/06/extends%EC%99%80-implements%EC%9D%98-%EC%B0%A8%EC%9D%B4.html

TAG •
?

  1. Image Upload

    http://imgur.com https://snag.gy/ https://postimages.org/ko/ http://imgur.top/ Clipboard 이미지의 업로드 https://blog.joostory.net/460
    Date2019.07.05 CategoryWeb Design Views44107
    Read More
  2. TensorFlow

    ‘함께하는 딥러닝 컨퍼런스’ 발표 자료입니다. Enjoy! slide: http://bit.ly/keras-in-tf2 script: http://bit.ly/keras-in-tf2-script #Reference https://tensorflow.blog/
    Date2019.07.05 CategoryDeep Learning Views1165
    Read More
  3. Get PyCharm Student Free License (파이참 무료 라이센스 받기)

    Requirement (필요사항) - university domain email adress (학교 도메인으로 된 이메일 주소) such as OOO@OOO.ac.kr / OOO@OOO.edu 1. go to https://www.jetbrains.com/shop/eform/students 2. fill the blank and click the button, "apply for free products" 3. co...
    Date2019.06.19 CategoryPyThon Views99627
    Read More
  4. How to add an external jar file in Android Studio

    To sum it up, when adding an external jar file in Android Studio: Copy jar to root/project/libs folder; Right-click and add as library; Add the jar to root/project/build.gradle (something like compile files('libs/test-jar-to-import.jar')); Mak...
    Date2015.08.06 CategoryCoding Views7421
    Read More
  5. No Image

    extends, interface, implements 의 정의

    A class implements an interface. An interface is an abstract class that only contains method signatures and constant declarations. An interface doesn't contain method definitions and can't be instantiated. A class extends another class. The new class ...
    Date2015.08.05 CategoryEngineering Views14264
    Read More
  6. No Image

    Android 단축키 팁 (생산성 최적화)

    import 정리: ctrl+alt+O 자동 완성/수정 import (show intention actions and quick-fixes): alt+Enter 이름 바꾸기 (Refactoring): shift+F6 자동완성 ctrl+ space 양식 정렬: ctrl+alt+L 메소드 오버라이드 (Override method): ctrl+o 인터페이스 구현 (Implement met...
    Date2015.08.05 CategoryEngineering Views5302
    Read More
  7. No Image

    Better Quality Images from Figures

    If you want better quality images from your figures, I would suggest downloading the submission Myaa by Anders Brun on The MathWorks File Exchange. It allows you to create anti-aliased graphics in MATLAB. Here's a screenshot from the submission illust...
    Date2015.02.03 CategoryEngineering Views5773
    Read More
  8. No Image

    "getframe" not working on 64-bit Windows properly

    Try this, but don't use a docked figure. Just use GETFRAME the normal way, but switch to software rendering of OPENGL. You should still be able to use transparency. opengl('software') #Source: http://www.mathworks.com/matlabcentral/answers/9000-cannot...
    Date2015.02.03 CategoryEngineering Views7489
    Read More
  9. No Image

    msg_make_directory_failed

    # Issuewhen you try to easy install on XE, it doesn't work with popup "msg_make_directory_failed" # Solution1. Go to Admin -> Settings -> FTP Account Information 2. Type the XE Path from the the directory you confront first when you access your FTP a...
    Date2011.09.22 CategoryEngineering Views15624
    Read More
  10. No Image

    2진수 <-> 8 진수, 16 진수 변환

    앞서 10 진수를 기준으로 2,8,16 진수의 변환을 알아 보았습니다. 이번에는 2진수를 8진수와 16진수로 변환하는 방법과 8진수,16진수를 2진수로 변환하는 방법을 알아 봅니다. 1. 2진수를 16진수로 변환하기. 2진수로 데이터가 저장되는 정보의 최소 단위인 비트가 4개 ...
    Date2011.09.17 CategoryReferences Views99505
    Read More
  11. No Image

    Align <Div> at center

    .body { text-align: center; } .body .container {margin: 0 auto; } <div class="body"> <div class="container">{contents}</div> </div> div 가운데 정렬하기 body안에 container를 가운데에 정렬함
    Date2011.08.12 CategoryEngineering Views19452
    Read More
  12. No Image

    [On2 Salsa - Beginner] Outside Turn, Close Cross Body Lead, Inside Turn

    Instructor : 태수&무아 (SkyLatin) Instruction : Holding - Outside Turn - Close Cross Body Lead (C-CBL) - Close Inside Turn
    Date2011.08.11 CategorySalsa Views23074
    Read More
Board Pagination Prev 1 2 3 Next
/ 3