JAVA/Basic

[스터디할래? Java 06]상속

[스터디할래? Java] 목차

이글은 백기선님 스터디 할래? 스터디를 뒤늦게 따라간 기록입니다.

스터디할래 링크 >> https://github.com/whiteship/live-study

이필기를 시작으로 공부했습니다 >>  https://leemoono.tistory.com/20 

여기 없는내용은 스터디 할래 강의 내용 혹은 제가 java Doc보고작성하거나 예제를 만들어 추가했습니다.

그외는 같이 출처가 써있습니다. 

자바상속 특징 다중상속 금지 : extends A, B   X
최상위 클래스 Object
디스패치  프로그램이 어떤 메소드를 호출할 것인가를 결정하여 그것을 실행하는 과정. 
- 동적 디스패치
- 정적 디스패치
Static Dispatch
정적 디스패치
어떤 메소드 실행될지 컴파일시점에서 알수 있음. 
static class Do{
void run(){}
void run(int number){}
}
Do.run();  <<<  정적디스패치는 ... 메소드 오버로딩의 경우. 
Dynamic Method Dispatch
동적 디스패치
컨파일타임에 알수 없는 메서드 의존성을 런타임에 늦게 바인딩
abstract class Do{
void run(){}
}
class MoningDo extends Do{
  @Overried
   void run(){ System.out.println("1"); }
}
class EveningDo extends Do{
  @Overried
   void run(){ System.out.println("2"); }
}
EveningDo ed = new EveningDo();
ed.run()  <<<<< 컨파일때는 알수 없고, 런타임때 알수 있다. 
바이트코드 : imvokvirtual : 동적디스패치
cf) 바이트코드 : imvorkspecial : 생성자 호출. 
더블 디스패치 동적 디스패치 두번 발생 
- 방문자 패턴: visitor partten 더블 디스패치 사용한 대표적 패턴.  
interface Post{
  void postOn(SNS sns);
}
class Text implements Post{
  public void postOn(Sns sns){ sns.post(this);}
}
class Picture implements Post{
  public void postOn(Sns sns){ sns.post(this);}
}
--------------------------- POST 구현하는클래스2개 postOn 생성. 
interface SNS{
  void post(Text text);
  void post(Picture picture);
}
class Facebook implements SNS{
   public void post(Text text){}
   public void post(Picture Picture){}
}
class Twitter implements SNS{
  public void post(Text text){}
   public void post(Picture Picture){}
}
--------------------------상기 상속받은 클래스를 매개변수로 쓰는 SNS 상속클래스 2개

public static void main(String[] args) {
     List<Post> posts = Arrays.asList(new Text(), new Picture()); 
     List<SNS> sns = Arrays.asList(new Facebook(), new Twitter());
     posts.forEach(p -> sns.forEach(s -> p.postOn(s)));
     //1. 어떤 구현체의 PostOn. 2. 어떤 SNS의 post  : 두번발생. 
}
출처 : https://blog.naver.com/swoh1227/222181505425
방문자 패턴 visitor pattern 
- SAX Parser  (cf _DOM Parser)



final class
variable
method
Object 클래스 clone: 해당객체 복제본생성
finalize()  해당객체 더는 아무도 참조지 않아 GC 호출함
notify()  해당객체 대기하고 있는 스레드 다시실행 할때 호출
wait()  notify, notifyall 메소드 호출전까지 현재 스레드 일시적 대기.  
varargs 가변인자, 변수의 마지막선언
내부적으로 배열로 받음. 
String... message  ==  String[] message
-------------------
void sum (String A, String...str){}
void sum (String...str){}
컴파일에러. 
------------------
var = variable
args = 아그 독립변수. 변수 독립변수. 
UML 상속 : 실선
구현 : 점선

- 클래스이름
- 필드내용
- 메소드 내용

객체지향의 사실과 오해, 오브젝트- 조영호저

dispatch : 보내다. 

 

 

웹 uml 툴 : https://app.diagrams.net/

public class Object {

    private static native void registerNatives();
    static {
        registerNatives();
    }
    public final native Class<?> getClass();
    public native int hashCode();
    public boolean equals(Object obj) {
        return (this == obj);
    }
    protected native Object clone() throws CloneNotSupportedException;

    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    public final native void notify();
    public final native void notifyAll();
    public final native void wait(long timeout) throws InterruptedException;
    public final void wait(long timeout, int nanos) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos > 0) {
            timeout++;
        }

        wait(timeout);
    }
    public final void wait() throws InterruptedException {
        wait(0);
    }
    protected void finalize() throws Throwable { }
}

학습할 것 (필수)

  • 자바 상속의 특징
  • super 키워드
  • 메소드 오버라이딩
  • 다이나믹 메소드 디스패치 (Dynamic Method Dispatch)
  • 추상 클래스
  • final 키워드
  • Object 클래스