in another class i used:
CoffeeCup original = new CoffeeCup();
original.add(75); // Original now contains 75 ml of coffee
CoffeeCup copy = (CoffeeCup) original.clone();
Now i got exact copy of CoffeeCup.
my question is: how the application is creating an subclass object(CoffeeCup) when I call super.clone().
As per my understanding if we call super.clone() that means we are calling Object.clone() -- if that is the case how it is creating the object of sub class?
Is there any underlying implementation that Object class uses for creating the subclass object?
All you need to know is that Object.clone() will simply create a new object of the exact same type (so in your case CoffeeCup) and copies all fields by using simple assignments. For example:
Line 11 could be replaced with the following:
There are three big differences though:
1) when you use Object.clone(), a sub class can call super.clone() and it will not return an instance of Test but an instance of that sub class.
2) Object.clone() does not call a constructor so no constructor code is executed
3) Object.clone() can also copy final fields