Código fuente del programa ConstructorRecursion
Ver la entrada correspondiente en el siguiente enlace:
Java: creando objetos - Parte1
package pruebas; import java.io.PrintStream; public class ConstructorRecursion { public static String echoAndPrint(String aMessage) { System.out.format("echoAndPrint: %s%n", aMessage); return aMessage; } public static void main(String[] args) { final PrintStream out= System.out; Derived aux= new Derived(); out.format("A derived object: %s%n", aux); } public static class Root { final protected String constant= "Constant attribute."; public Root() { //Compiler calls super() automatically. echoAndPrint("Root constructor"); } } public static class Base extends Root { //Yes, I'm using the own attribute value to initialize it. private String variable= echoAndPrint("Initial value: " + this.variable); public Base(String aValue) { //Compiler calls super() automatically. this.variable= echoAndPrint(aValue); } @Override public String toString() { String str= String.format("%s variable<%s> constant=<%s>" , super.toString() , this.variable , this.constant ); return str; } } public static class Derived extends Base { private String extra; public Derived(String aValue) { super( echoAndPrint("aValue= " + aValue) ); } public Derived() { this( echoAndPrint("No arguments") ); //this( super.constant );//Error: cannot reference this before supertype constructor has been called //this( this.extra );//Error: cannot reference this before supertype constructor has been called } } }//End ConstructorRecursion
No hay comentarios:
Publicar un comentario