2011-05-10 9 views
1

같은 일을의 목적은 무엇인가 :혼합 생성자의 목적은 무엇입니까?

Employee a = new OverTimeEmployee(); 

또는 OverTimeEmployee 직원의 서브 클래스가

OverTimeEmployee a = new Employee(); 

?

무엇이 적절한 이름입니까? 혼합 생성자가 맞지 않다고 생각합니다.

+0

도움과 빠른 답변에 감사드립니다. – mergesort

+4

'OverTimeEmployee a = new Employee();' "OverTimeEmployee는 employee의 하위 클래스입니까?" - 그건 컴파일되지 않을거야. – Lumi

+0

@ 마이클, 그게 내 대답 – Neal

답변

4

오브젝트 상속이라고합니다.

Polymorphism과 함께 객체 지향 프로그래밍의 주요 기능 중 하나입니다. 그래서 코드에서

:

class Employee { 
    ... 
} 

class OverTimeEmployee extends Employee { 
    ... 
} 

그래서 이유는이 작업을 수행 할 수 있습니다 OverTimeEmployeeEmployee의 일종이기 때문에

Employee a = new OverTimeEmployee(); 

입니다.

나는 모든 Employee 's이 (가) OverTimeEmployee이기 때문에 당신은 당신이 두 번째 예제에서했던 일을 할 수 있다고 생각하지 않으며, 당신은 오류을 얻을 것이다.

+0

흠, 어쩌면 polymorphism (http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming) 여기에 언급되어야 언급했다. – Daff

+0

@Daff 방금 언급 : 감사합니다. – Neal

1

의 하위 클래스 인 경우 OverTimeEmployee a = new Employee();을 사용할 수 없습니다. 그건 컴파일되지 않습니다.

Employee a = new OverTimeEmployee();은 객체 지향 프로그래밍 및 상속의 핵심 요소입니다.

2
Employee a = new OverTimeEmployee(); 

은 '다형성'이라고합니다.

다형성 : "한 이름, 여러 양식".

다형성 (Polymorphism)은 동작 또는 메서드가 처리중인 개체를 기반으로 다른 작업을 수행 할 수있는 기능입니다.

OverTimeEmployee가 Employee의 하위 클래스 인 경우 (예 : OverTimeEmployee extends Employee)이 작업을 수행 할 수 있습니다. 기본적으로 상속이있는 경우에만 사용할 수 있습니다. 다형성은 메서드 오버로딩과 함께 사용됩니다.

이유 : 다형성의 경우 호출 할 메서드의 버전을 확인하기 위해 참조 형식이 아닌 실제 개체 형식이 사용됩니다. 메소드는 컴파일시에 바인드됩니다 (오버라이드의 경우 런타임과 반대입니다).

printDescription()이라는 메소드가 OverTimeEmployee에 있고 RegularEmployee (Employee의 하위 클래스가 하나)라고 가정 해 보겠습니다. OverTimeEmployee 클래스의 메서드에서 int overtimerate을 인쇄하고 RegularEmployeeString perks이라고 인쇄한다고 말합니다.그런 다음

class OverTimeEmployee { 
    int overtimerate; 
    . 
    . 
    . 

    void printDescription() { 
    System.out.println("I am overtime employee with pay rate " + overtimerate); 
    } 
} 

class RegularEmployee { 
     String perks; 
     . 
     . 
     . 

     void printDescription() { 
     System.out.println("I am regular employee with perks " + perks); 
    } 
} 

이 작업을 수행 :

OverTimeEmployee ot = new Employee(20); // initializing orvertimerate as 20 

RegularEmployee rt = new Employee("Free parking"); // initializing perks as "Free parking" 

ot.printDescription()

I am overtime employee with pay rate 20 

rt.printDescription()

또한
I am regular employee with perks Free parking 

는 점에 유의 인쇄 할 인쇄됩니다, OverTimeEmployee a = new Employee(); 공동하지 않습니다 OverTimeEmployee는 Employee의 하위 클래스이기 때문에 mplie입니다. 희망이 도움이됩니다.

1

개체에 대한 런타임 참조가 호출되는 메서드를 결정하는 다형성에 사용할 수 있습니다. 따라서 Employee와 OverTimeEmployee에 모두 수입 방식이 있고 Employee 프로그램 실행 중 OverTimeEmployee에 대한 참조가 포함되어 있으면 OverTimeEmployee의 수입 방식이 호출됩니다.

관련 문제