0

hi im trying to make a simple deep cloning example in java

public class Deepcloning implements Cloneable
{
    public Shallowcloning shallowcopy;
    public Deepcloning() {
    }
    public Shallowcloning getShallowcopy() {
        return shallowcopy;
    }
    public void setShallowcopy(Shallowcloning shallowcopy) {
        this.shallowcopy = shallowcopy;
    }
    public String getEmployee() {
        return employee;
    }
    public void setEmployee(String employee) {
        this.employee = employee;
    }
    private String employee;

    public Object clone() throws CloneNotSupportedException{

        Deepcloning shls=(Deepcloning)super.clone();
        shls.setShallowcopy((Shallowcloning)shallowcopy.clone());
        return shls;
    }
}

and in the main implementation method

public class Clonningimplementation {

    public static void main(String[] args) {

        try {

            Deepcloning dp1 = new Deepcloning();
            dp1.setEmployee("solomon");

            dp1.getShallowcopy().setAge(11);
            dp1.getShallowcopy().setSalary(3000);


            System.out.println("orignal copy employee" + dp1.getEmployee());
            System.out.println("orignal copy employee" + dp1.getShallowcopy().getAge());
            System.out.println("orignal copy employee" + dp1.getShallowcopy().getSalary());
        } catch (ClonenotSupportedException e) {
            e.printstacktrace();
        }

        ...
    }
    ...
}

while running this code im getting null pointer exception. in deep cloning im supposed to clone the reference that too i have done still didnt getting the result any help would be appreciated

Konrad Krakowiak
  • 12,285
  • 11
  • 58
  • 45
user3878073
  • 81
  • 1
  • 1
  • 7

2 Answers2

0
dp1.getShallowcopy().setAge(11);

You are directly calling methods on shallowcopy reference without instantiating it. By default it's value is null. calling methods on null reference will give NPE.

You need to do

Deepcloning dp1=new Deepcloning(); dp1.setEmployee("solomon");
dp1.setShallowcopy(new Shallowcloning ());
dp1.getShallowcopy().setAge(11);;
dp1.getShallowcopy().setSalary(3000);
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

By default every object initializes to null and is your shallowcopy.

You are calling getter for shallowcopy as below:

dp1.getShallowcopy().setAge(11);

But you have never setted value for shallowCopy and hence when you call this method it gets evaluated as null.setAge(11); and calling a method on null gives you null pointer exception.

To avoid this, you might need to set Shallowcloning using

Deepcloning dp1=new Deepcloning(); 
dp1.setEmployee("solomon");
dp1.setShallowcopy(...);

This applies to clone method as well.

SMA
  • 36,381
  • 8
  • 49
  • 73