Forward Reference no J2SDK1.4.1

6 respostas
dsuruagy

Olá!

Estava estudando o assunto “Instance Initializers” e me deparei com uma questão no livro “A Programmer’s Guide to Java Certification”. Respondi corretamente: “O código não irá compilar”. Porém, implementei o danado e ele compilou!
Alguém poderia me explicar por que este código compila no J2SDK 1.4.1_02 da Sun, mas dá o erro “Can’t make forward reference to m in class ForwardReference.” em versões mais antigas do JDK(1.3) ou no Eclipse?
Será algum bug do SDK oficial?
O que eu deveria responder na prova de ‘Programmer 1.4’?

Valeu!

public class ForwardReference {
	String msg(String m) {
		System.out.println(m);	return m;
	}
	
	ForwardReference() {
		m = msg("1");
	}
	
	{	m = msg("2");
	}
	
	String m = msg("3");
	
	public static void main(String args[]) {
		ForwardReference fr = new ForwardReference();
	}
}

6 Respostas

A

dsuruagy,
testei aqui com o J2SDK 1.4.0_01 e deu o seguinte erro:

ForwardReference.java:10: illegal forward reference
{ m = msg(“2”);
^

Ou seja, parece que compila só na versão 1.4.1. O porquê não sei…
Valeu.

R

Eu nao estou bem certo, mas acho que talvez seja mesmo um BUG da versao 1.4.0 … porque segundo me consta a declaracao de variaveis na classe nao tem que estar exatamente no inicio do codigo…

Eu tenho a 2a. edicao do Core Java 2 (1.2 ainda… ) e todos os exemplos dos 2 volumes a declaracao das variaveis é feita sempre no final das classes que sao criadas pelos autores…

E tem mais… tanto deve ser um bug que corrigiram (ufa!!) a partir da versao 1.4.1 …

:roll:

marciolx

Segundo o livro da lei, a JLS, APENAS NO CASO de static initializers as variáveis têm que ser declaradas na ordem em que são utilizadas:

8.3.2.3 Restrictions on the use of Fields during Initialization
The declaration of a member needs to appear before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
The usage is not on the left hand side of an assignment.
C is the innermost class or interface enclosing the usage.

Em qual página está essa pergunta?

R

que livro é esse?? :?: :shock:

marciolx

http://java.sun.com/docs/books/jls/

marciolx

citando Bruce Eckel na última edição do TIJ (que é o que eu tenho ao alcance no momento):

Capítulo: Initialization and cleanup

Order of initialization

Within a class, the order of initialization is determined by the order that the variables are defined within the class. The variable definitions may be scattered throughout and in between method definitions, but the variables are initialized before any methods can be called—even the constructor.

Criado 23 de abril de 2003
Ultima resposta 23 de abr. de 2003
Respostas 6
Participantes 4