[3197] in java-interest

home help back first fref pref prev next nref lref last post

Object Creation using Class.newInstance()

daemon@ATHENA.MIT.EDU (Suresh Srinivasan)
Thu Nov 2 21:28:01 1995

Date: Thu, 2 Nov 1995 17:14:33 -0500
From: suresh@thomtech.com (Suresh Srinivasan)
To: java-interest@java.sun.com

Hello all:

I'm not a OO programmer (yet!) so these may be easy to answer.

Suppose I have an abstract class say Shape which is subclassed
into Rect, Arc, Ellipse, etc. somewhat analogous to the GraphicsTest
demo.

abstract class Shape {
  abstract void draw();
  abstract void fill();
...
}

class Rect extends Shape {
  void draw() {...}
  void fill() {...}
}

And I want to stuff an array with Shapes so I can call its abstract
methods without worrying about the type of object it represents.
The type of shape I want to put in is specified in another array
containing the string representation of the subclass name as in:

String shapeNames[] = {"Rect", "Arc", "Rect", "Ellipse"};

Shape shapeArray[] = new Shape[shapeNames.length];
for (int i=0; i<shapeNames.length; i++) {
  Class c = Class.forName(shapeNames[i]);
  shapeArray[i] = new (Shape)c; // option A
  shapeArray[i] = (Shape) c.newInstance(); // option B
}

Option A generates a compile time error of the form:
'new(...)' not supported.

Option B compiles OK, except my shape constructors take arguments
and the newInstance method clearly does not.

Anybody see a way to do this more elegantly?

Another related question, is there a notion of abstract instance
variable?  Can I access an instance variable of Rect, say, if I
have a Shape reference?  (I'm assuming not).  For example:

for (int i=0; i<shapeNames.length; i++) {
  shapeArray[i].size += 1;
}

Must 'size' be an instance variable in Shape, an abstract class?

Thanks for reading this and any help you can provide,

--Suresh

-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post