1

I want to ask you how can i copy firstClass objects to secondClass objects?

Is this possible to figure it out by using clone()?

The situation looks like this:

I have a class f.x. firstClass. And I need to clone firstClass objects to secondClass objects (and these cloned objects must be stored into array)

Thanks

EDITED:

sorry for a little information. But my task looks like this:

Write a Garage class whose objects can hold up to some number of Vehicle objects in an array. Make Garage a Cloneable type, and write a proper clone method for it. Write a Garage.main method to test it.

3
  • Would you like value copy or pointers are fine? Commented Oct 21, 2013 at 18:25
  • what do firstClass and secondClass look like? does one inherit from another? Commented Oct 21, 2013 at 18:26
  • I have edited my post for more info. Commented Oct 21, 2013 at 19:34

3 Answers 3

3

It's not cloning. If you have two unrelated classes, the best you can do is write a constructor for SecondClass that takes FirstClass object as an argument and writes all the values into the proper fields:

public SecondClass (FirstClass source){
  this.valueA = source.getValueA();
  this.valueB = source.getBValue();
  this.valueC = source.getProperCValue();
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

3

By convention, Object.clone() method and its overrides should always return an object of the original type.

x.clone().getClass() == x.getClass()

So it should be impossible to create an object of different type if clone() is properly implemented and used.

Comments

1

something like this?!

class Foo{
  private String bar;
  public Object clone(){
    Foo f=new Foo();
    f.setBar(this.bar);
    //filling and copy the f attributes
    guys.add(f);
  }
   ///
   private final static List<Foo> guys=new ArrayList<>();
   ///
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.