0

Got some incomprehensible exercise in my book.

"Create a class with a non-default constructor (one with arguments) and no default constructor (no "no-arg" constructor). Create a second class that has a method that returns a reference to an object of the first class. Create the object that you return by making an anonymous inner class that inherits from the first class."

Can anyone come out with a source code?

Edit: I don't understand what the final source code should look like. And I came with this one:

class FirstClass
{
    void FirstClass( String str )
    {
        print( "NonDefaultConstructorClass.constructor(\"" + str + "\")" );
    }
}

class SecondClass
{
    FirstClass method( String str )
    {
        return new FirstClass( )
        {
            {
                print( "InnerAnonymousClass.constructor();" );
            }
        };
    }
}

public class task_7
{
    public static void main( String[] args )
    {
        SecondClass scInstance = new SecondClass( );
        FirstClass fcinstance = scInstance.method( "Ta ta ta" );
    }
}
4

1 回答 1

1

Honestly, the exercise is quite concise unless you do not know or understand the definition of an inner class. You can find an example of an anonymous inner class here:

http://c2.com/cgi/wiki?AnonymousInnerClass

Otherwise, this concise example illustrates the problem:

/** Class with a non-default constructor and no-default constructor. */
public class A {
    private int value;

    /** No-arg constructor */
    public A() { 
        this.value = 0;
    }

    /** Non-default constructor */
    public A(int value) { 
        this.value = value;
    }

    public int getValue() { 
        return this.value;
    }
}

/** Class that has a method that returns a reference to A using an anonymous inner class that inherits from A. */
public class B {
    public B() { ; }

    /** Returns reference of class A using anonymous inner class inheriting from A */
    public A getReference() {
         return new A(5) {
              public int getValue() {
                  return super.getValue() * 2;
              }
         };
    }
}
于 2012-08-25T16:35:35.490 回答