Example 8.3-1. Multiply Inherited Fields
A class may inherit two or more fields with the same name, either from two interfaces or from its superclass and an interface. A compile-time error occurs on any attempt to refer to any ambiguously inherited field by its simple name. A qualified name or a field access expression that contains the keyword super (§15.11.2) may be used to access such fields unambiguously. In the program:
package main;
public class Test extends SuperTest implements Frob {
public static void main(String[] args) {
new Test().printV();
}
void printV() {
System.out.println(v); // The field v is ambiguous
}
}
interface Frob {
float v = 2.0f;
}
class SuperTest {
int v = 3;
}
the class Test inherits two fields named v, one from its superclass SuperTest and one from its superinterface Frob. This in itself is permitted, but a compile-time error occurs because of the use of the simple name v in method printV: it cannot be determined which v is intended.
The following variation uses the field access expression super.v to refer to the field named v declared in class SuperTest and uses the qualified name Frob.v to refer to the field named v declared in interface Frob:
컴파일 결과는 다음과 같다.
2.5
상속받는 두 개의 필드가 같은 타입, 같은 값, 심지어 둘다 final 할지라도, 컴파일에러가 난다.
Example 8.3-2. Re-inheritance of Fields
If the same field declaration is inherited from an interface by multiple paths, the field is considered to be inherited only once. It may be referred to by its simple name without ambiguity. For example, in the code:
'자바' 카테고리의 다른 글
[스레드] 1. 멀티 스레드 개념 (0) | 2021.12.29 |
---|---|
8.3 Field Declarations (2) (0) | 2021.10.11 |
[자바] 8.2 클래스 멤버 (0) | 2021.10.02 |
람다 표현식과 this 키워드에 관하여 (0) | 2021.09.26 |
자바 Stream API (0) | 2021.09.25 |