Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.47 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. /****************** Exercise 15 *****************
  2.  * Create a class with a non-default constructor
  3.  * (one with arguments) and no default constructor
  4.  * (no "no-arg" constructor). Create a second class
  5.  * with a method that returns a reference to
  6.  * an object of the first class. Create the object
  7.  * you return by making an anonymous inner
  8.  * class inherit from the first class.
  9.  ***********************************************/
  10. class Ferret
  11. {
  12. //    private String color;         // this didn't work
  13.     String color;
  14.     Ferret( String color ) { this.color = color; };
  15.     public String getColor() { return color; };
  16. }
  17.  
  18. public class ex15
  19. {
  20.     public static Ferret newFerret( String color )
  21.     {
  22.         return new Ferret( color ) {};
  23.     }
  24.     public static Ferret greenFerret()
  25.     {
  26.         return new Ferret( "green" ) {
  27.             // overriding method
  28.             public String getColor() { return "weird: " + color; }
  29.         };
  30.     }
  31.     public static void main( String[] args )
  32.     {
  33.         Ferret f1 = newFerret( "chartreuse" );
  34.         System.out.println( f1.getColor() );
  35.         Ferret f2 = greenFerret();
  36.         System.out.println( f2.getColor() );
  37.     }
  38. }
  39. /* OUTPUT:
  40. chartreuse
  41. weird: green
  42.  
  43. Compiler output when Ferret.color is private:
  44.  
  45. ex15.java:19: color has private access in Ferret
  46.             public String getColor() { return "weird: " + color; }
  47.                                                           ^
  48. 1 error
  49.  
  50. */