tags:

views:

43

answers:

3

All,

I'm going through the Friedman & Felleisen book "A Little Java, A Few Patterns". I'm trying to type the examples in DrJava, but I'm getting some errors. I'm a beginner, so I might be making rookie mistakes.

Here is what I have set-up:

public class ALittleJava {
  //ABSTRACT CLASS POINT
  abstract class Point {
    abstract int distanceToO();
  }
  class CartesianPt extends Point {
    int x;
    int y;
    int distanceToO(){
      return((int)Math.sqrt(x*x+y*y));
    }
    CartesianPt(int _x, int _y) {
    x=_x;
    y=_y;
    }
  }
  class ManhattanPt extends Point {
    int x;
    int y;
    int distanceToO(){
      return(x+y);
    }
    ManhattanPt(int _x, int _y){
      x=_x;
      y=_y;
    }
  }
}

And on the main's side:

public class Main{
  public static void main (String [] args){
    Point y = new ManhattanPt(2,8);
    System.out.println(y.distanceToO());
  }
}

The compiler cannot find the symbols Point and ManhattanPt in the program.

If I precede each by ALittleJava., I get another error in the main, i.e.,

an enclosing instance that contains ALittleJava.ManhattanPt is required

I've tried to find ressources on the 'net, but the book must have a pretty confidential following and I couldn't find much.

Thank you all.

JDelage

+1  A: 

Make your inner classes static, otherwise you'll need to access your inner classes from an instance of ALittleJava, such as ALittleJava java = new ALittleJava(), which doesn't seem to match your use case.

static inner classes cannot see the members of their enclosing class, and if classes are nonstatic, conversely, they CAN see the members of their enclosing class, and an enclosing instance is in fact required.

Stefan Kendall
The `abstract` is core to the book though.
JDelage
A: 

Is this code copied verbatim from the book? If so, this structure is a little unconventional - usually classes are defined one per file (Point.java, CartesionPt.java, etc.), and only set up this way (using inner classes) in special circumstances.

Ken Liu
The book doesn't describe how to set up the code, what to put into different files, etc. Everything but the first line is verbatim from the book.
JDelage
Stefan Kendall's answer is correct - main() should be declared in your class ALittleJava instead of in its own class.
Ken Liu
IMO, the best introductory book on Java is "Thinking in Java" by Bruce Eckel. Friedman/Felleisen are better known for their books on lisp.
Ken Liu
A: 

Now that I think about it, ALittleJava is a crazy class name, unless it's meant to be the main class.

If you put public static void main( String[] args ) WITHIN ALittleJava, you should be able to use those classes.

Stefan Kendall