0
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 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.

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
shashikiran
  • 369
  • 1
  • 5
  • 17
  • 2
    By the way, are you familiar with [generics](http://download.oracle.com/javase/tutorial/java/generics/index.html)? There's no reason to use raw types in new code; you should be using `List stmts = new ArrayList();` on the first line, for example, and probably a `FlatIterator` too. – Andrzej Doyle Jun 16 '11 at 07:56
  • Doesn't look like the code is headed in a good direction - messing around with `clone()` etc. There's got to be a cleaner way to achieve what you want. – Bohemian Jun 16 '11 at 07:58
  • And while I'm nit-picking, the naming convention in Java is that methods and variables start with lowercase letters, with initially-capitalised identifiers being reserved for classes/interfaces. In that respect your `CreateNewStatements` method would look more natural as `createNewStatements`, taking a parameter called `l`. (This seems pedantic but it's surprising how much harder it is to read/understand code that breaks naming conventions, as your brain keeps going "that's a class - no, wait...") – Andrzej Doyle Jun 16 '11 at 07:59

1 Answers1

2

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();
}
Community
  • 1
  • 1
Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228