저는 downcast
참조 변수뿐만 아니라 Polymorphism
주제의 Java 책을 읽었습니다. 그러나, 나는 downcasting의 개념을 이해하는 것에 꽤 빠져있다. 다음은 제가 따르는 예제의 uml입니다. 자신의 기본급에 10 %의 증가를 주어진에 그들이 BasePlusCommissionEmployee
의 모든 개체다형성 및 다운 캐스팅 질문
. 다른 Employee
하위 클래스는 정상입니다. PayrollSystemTest
에는 응용 프로그램을 실행하는 기본 방법이 있습니다.
// Fig. 10.9: PayrollSystemTest.java
// Employee hierarchy test program.
public class PayrollSystemTest
{
public static void main(String[] args)
{
// create subclass objects
SalariedEmployee salariedEmployee =
new SalariedEmployee("John", "Smith", "111-11-1111", 800.00);
HourlyEmployee hourlyEmployee =
new HourlyEmployee("Karen", "Price", "222-22-2222", 16.75, 40.0);
CommissionEmployee commissionEmployee =
new CommissionEmployee(
"Sue", "Jones", "333-33-3333", 10000, .06);
BasePlusCommissionEmployee basePlusCommissionEmployee =
new BasePlusCommissionEmployee(
"Bob", "Lewis", "444-44-4444", 5000, .04, 300);
System.out.println("Employee processed individually:");
System.out.printf("%n%s%n%s: $%,.2f%n%n",
salariedEmployee, "earned", salariedEmployee.earnings());
System.out.printf("%s%n%s: $%,.2f%n%n",
hourlyEmployee, "earned", hourlyEmployee.earnings());
System.out.printf("%s%n%s: $%,.2f%n%n",
commissionEmployee, "earned", commissionEmployee.earnings());
System.out.printf("%s%n%s: $%,.2f%n%n",
basePlusCommissionEmployee,
"earned", basePlusCommissionEmployee.earnings());
// create four-element Employee array
Employee[] employees = new Employee[4];
// initialize array with Employees
employees[0] = salariedEmployee;
employees[1] = hourlyEmployee;
employees[2] = commissionEmployee;
employees[3] = basePlusCommissionEmployee;
System.out.printf("Employees processed polymorphically:%n%n");
// generically process each element in array employees
for (Employee currentEmployee : employees)
{
System.out.println(currentEmployee); // invokes toString
// determine whether element is a BasePlusCommissionEmployee
if (currentEmployee instanceof BasePlusCommissionEmployee)
{
// downcast Employee reference to
// BasePlusCommissionEmployee reference
BasePlusCommissionEmployee employee =
(BasePlusCommissionEmployee) currentEmployee;
employee.setBaseSalary(1.10 * employee.getBaseSalary());
System.out.printf(
"new base salary with 10%% increase is: $%,.2f%n",
employee.getBaseSalary());
} // end if
System.out.printf(
"earned $%,.2f%n%n", currentEmployee.earnings());
} // end for
// get type name of each object in employees array
for (int j = 0; j < employees.length; j++)
System.out.printf("Employee %d is a %s%n", j,
employees[j].getClass().getName());
} // end main
} // end class PayrollSystemTest
책은 상기 루프 반복 배열 employees
대한 개선 및 각 반복에서 상기 어레이의 상이한 Employee
에 대한 참조를 할당 Employee
변수 currentEmployee
와 방법을 toString
및 earnings
을 호출한다고 설명한다. 결과적으로, 출력은 각 클래스의 특정 메소드가 호출되고 오브젝트 유형에 따라 실행 시간에 해석되는 것을 보여줍니다. BasePlusCommissionEmployee
의 방법 getBaseSalary
현재 Employee
개체 setBaseSalary
를 호출하기 위해
는 조건문은 객체 참조는 instanceof 연산자 및 경우를 이용하여 BasePlusCommissionEmployee
객체 조건이 사실 인 경우 확인하는 데 사용 객체는 언급 된 방법을 호출하기 전에 다운 케스트에서 Employee
to BasePlusCommissionEmployee
유형이어야합니다.
이 심각하게 우리가 서브 클래스 'toString
방법에 액세스 할 수 있기 때문에 저를 혼란스럽게하지만, 다른 방법, 즉 getBaseSalary
및 setBaseSalary
를 사용하기 위해 객체를 다운 캐스트 할 수있다? 왜 이런 경우입니까?
그래 나에게 너무 많은 의미가 있습니다. 그런데 왜 instanceof를 사용하는 것이 나쁜 습관이라고 말합니까? – Scorpiorian83
instanceof는 일반적으로 다형성을 적용하는 코드로 대체 할 수 있기 때문에 좋지 않습니다. GhostCat의 답변을 참조하십시오. 다시 말해서 : if (obj instanceof ClassA) {doA(); } else if (클래스 B의 obj 인스턴스) {doB(); }'ClassA와 ClassB의 수퍼 클래스에서'doStuff()'메소드를 정의하고 각 클래스에서 그것을 오버 라이딩하여 올바른 일을 한 다음 위의 코드를'obj.doStuff()'로 바꾸면 더 낫습니다. –