开发者

Setting up DrJava to work through Friedman / Felleisen "A Little Java"

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 hav开发者_Go百科e 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


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.


Make your file look like this:

//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;
  }
}
class Main {
  public static void main (String [] args) {
    Point y = new ManhattanPt(2,8);
    System.out.println(y.distanceToO());
  }
}

Then, in the "Interactions" tab type this command:

java Main


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜