开发者

Call a method of class using object of some other class in java

List CreateNewStatements(ForLoop L)
{
    List stmts = new ArrayList();
    FlatIterator iter = new FlatIterator(L.getBody());

    Traversable t1 = null;

    LoopUnroll l = new LoopUnroll(t1);

    while(iter.hasNext())
    {
        stmts.add(iter.next().clone());
    }
    return stmts;
}

The above code is giving the 开发者_JS百科error as "The method clone() from the type Object is not visible".

In the above code, iter.next() returns a statement(Eg. fx[i] = fx[i] + x) of type Object(built in into java library) using which I want to call the method clone(). The above code is written in a class LoopUnroll and clone() is a method defined in the class Statement.


clone() is protected on Object for exactly this reason - that you can't just call it on arbitrary objects. It's a bit of a hack, so that all classes can inherit the implementation of the method, but don't expose that behaviour by default. (See Why is the clone method protected in java.lang.Object? for more details.)

Anyway, if you actually want instances of your Statement class to be cloneable, you should do two things:

  1. Ensure the class implements Cloneable
  2. Redefine the clone method as public, and just defer to the superclass implementation. (This also gives you the chance to use covariant return types to prevent callers having to cast in most cases).

The latter is what actually makes the clone method visible, and would look something the following:

@Override
public Statement clone() {
    return (Statement)super.clone();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜