
Untitled
By: a guest on
May 7th, 2012 | syntax:
None | size: 1.47 KB | hits: 10 | expires: Never
/****************** Exercise 15 *****************
* Create a class with a non-default constructor
* (one with arguments) and no default constructor
* (no "no-arg" constructor). Create a second class
* with a method that returns a reference to
* an object of the first class. Create the object
* you return by making an anonymous inner
* class inherit from the first class.
***********************************************/
class Ferret
{
// private String color; // this didn't work
String color;
Ferret( String color ) { this.color = color; };
public String getColor() { return color; };
}
public class ex15
{
public static Ferret newFerret( String color )
{
return new Ferret( color ) {};
}
public static Ferret greenFerret()
{
return new Ferret( "green" ) {
// overriding method
public String getColor() { return "weird: " + color; }
};
}
public static void main( String[] args )
{
Ferret f1 = newFerret( "chartreuse" );
System.out.println( f1.getColor() );
Ferret f2 = greenFerret();
System.out.println( f2.getColor() );
}
}
/* OUTPUT:
chartreuse
weird: green
Compiler output when Ferret.color is private:
ex15.java:19: color has private access in Ferret
public String getColor() { return "weird: " + color; }
^
1 error
*/