Let’s clone in Java

Java Cloning

Java Cloning

소개

The Cloneable interface in java is a marker interface. It does have any method. But if we write a class as below, it gives a message to the jvm that the class can be cloned. The following code shows a simple object cloning process –







[코드]

package com.home.cloning;

공공의 클래스 CloneClass implements Cloneable {

INT 에이;

double B;

// This method calls Object’s clone().

CloneClass getClone() {

시도 {

// call clone in Object.

return (CloneClass) 슈퍼.clone();

} 잡기 (CloneNotSupportedException e) {

체계.밖으로.나서 println (” Cloning not allowed. ” );

return this;

}

}

}

[/코드]

Let us check the second example below.

[코드]

package com.home.cloning;

공공의 클래스 TestCloneObject {

공공의 무효 testIface() {

CloneClass x1 = 새로운 CloneClass();

CloneClass x2;

x1.a = 15;

x1.b = 35.05;

x2 = x1.getClone(); // clone x1

체계.밖으로.나서 println(” x1: ” + x1.a + ” ” + x1.b);

체계.밖으로.나서 println(” x2: ” + x2.a + ” ” + x2.b);

}

공공의 정적 인 무효 주(String args[]) {

TestCloneObject testCloneObject = 새로운 TestCloneObject();

// test via protected

testCloneObject.testIface();

}

}

In the above example, the method [코드] getClone [/코드] calls the [코드] clone [/코드] method in the object and returns the object. It must be noticed here that the object with is returned after the cloning mechanism has to be type casted into its appropriate type, in this case it is

[코드] CloneClass [/코드]

If the class is not implementing the cloneable interface, and we try to clone that object we get a

[코드] CloneNotSupportedException [/코드]

In the process of cloning, the constructor is not called rather an exact copy of the said object is created. But the object of which the clone is created, must implement the cloneable interface.

The 클래스 Object’s clone() method creates and returns a copy of the object, with the same class and with all the fields having the same values. However, [코드] Object.clone() [/코드] throws a [코드] CloneNotSupportedException [/코드] unless the object is an instance of a class that implements the marker interface Cloneable.

The default implementation of [코드] Object.clone()[/코드] performs a shallow copy. If a class requires a deep copy or some other custom behavior, 그것의 사용자 정의해야합니다 [코드] clone()[/코드] 방법들은 슈퍼 클래스의 사본을 얻을 후.







복제의 장점

복제 메커니즘 우리는 객체의 복사본을 생성 할 경우 현상 제의 추가 작업을 절약. 우리는 호출 할 필요가 없습니다 [코드] 새로운 [/코드] 객체의 운영자. 따라서 복제 개발자의 추가 처리 작업을 많이 절약. 개체의 복제는 개체의 정확한 사본입니다.

복제의 단점

복제 중 하나 단점은의 반환 형식 [코드] clone [/코드] 방법은 인 [코드] Object [/코드]. 따라서 타입 캐스팅은 생성 된 객체에 필요.

또 다른 단점은 액세스 할 수 없다는 것이다 [코드] clone [/코드] 추상적 인 유형에 대한 방법. 대부분의 인터페이스와 자바 추상 ​​클래스는 공개를 지정하지 않아도 [코드] clone [/코드] 방법. As a result, the [코드] clone [/코드] 물체의 실제 클래스가 알려져있는 경우에있어서 만 사용, which is against the abstraction principle of using the most generic type possible. For example, if one has a List reference in Java, one cannot invoke [코드] clone [/코드] method on that reference because List specifies no public clone() 방법. Actual implementations of List like ArrayList and LinkedList all generally have clone() methods themselves, but it is inconvenient and bad abstraction to carry around the actual class type of an object.

Cloning is a potentially dangerous action, as it can have some unintended side effects. e.g, if the object being cloned contains a reference variable say refObject, then in the cloned object, refObject will have the reference of the same object which the original object is referring to. If the clone makes a change in the contents of the refObject, then the change will be reflected in the original object as well. Consider the following example – If an object opens an I/O stream and is then cloned, then both of the two objects will be capable of operating on the same stream. Further, if one of these objects closes the stream, then the stream is closed for both and if the second object tries to write to it, this causes an error.

Since cloning can cause some problems, the [코드] clone [/코드] 방법. So the [코드] clone [/코드] method should be called from within a class which is implementing the [코드] cloneable [/코드] interface where the method calling the [코드] clone [/코드] method is made protected, or it must be explicitly overridden by the class which is public. In the example above we have seen cloning by making the [코드] clone [/코드] protected. The following example illustrates the cloning methodology via overriding –

[코드]

package com.home.cloning;

공공의 클래스 CloneViaOverRiding implements Cloneable {

INT 에이;

double B;

// clone() is now overridden and is public.

공공의 Object clone() {

시도 {

// call clone in Object.

return 슈퍼.clone();

} 잡기 (CloneNotSupportedException e) {

체계.밖으로.나서 println(“Cloning not allowed.”);

return this;

}

}

}

[/코드]

Now check the next example below.

[코드]

package com.home.cloning;

공공의 클래스 TestCloneObject {

공공의 무효 testPublic() {

CloneViaOverRiding x1 = 새로운 CloneViaOverRiding();

CloneViaOverRiding x2;

x1.a = 10;

x1.b = 20.98;

// here, clone() is called directly.

x2 = (CloneViaOverRiding) x1. clone ();

체계.밖으로.나서 println(“x1: ” + x1.a + ” ” + x1.b);

체계.밖으로.나서 println(“x2: ” + x2.a + ” ” + x2.b);

}

공공의 정적 인 무효 주(String args[]) {

TestCloneObject testCloneObject = 새로운 TestCloneObject();

// test via 공공의

testCloneObject.testPublic();

}

}

[/코드]

In this example the method, the method [코드] clone [/코드] of the object class is overridden that is why it is declared public in contrast to the earlier example, where the [코드] getClone [/코드] does not have any access modifiers making it accessible only at the package level.

In either of these two approaches, implementing the cloneable interface is mandatory.

The side effects caused by cloning are sometimes difficult to identify in the initial level. It is easy to think that a class is safe for cloning when it actually is not. In general, is not advised to implement the Cloneable interface for any class without having a solid business ground .







Alternative to cloning

Cloning mechanism has few alternatives –

  • copy constructor – a copy constructor is a constructor which accepts another instance of the same class as a parameter.
  • factory method – these methods are not always adequate when the concrete type of the cloned object is not known in advance.
  • Use of serialization and deserialization is another alternative to using clone.

결론

  • Object cloning is the mechanism of creating a copy of an existing object
  • Cloning follows the shallow copy mechanism
  • Closing saves some extra tasks of the developer
  • Once the cloning is done the created clone object is required to explicitly casted in to the required type
  • Cloning has some side effects e.g if an object which is cloned has a reference to another object, and the new cloned object modifies the object which being referenced, then the original object also gets changed.
  • Cloning mechanism has some alternatives – the copy constructor, factory method, serialization and de-serialization.
Tagged on: ,
============================================= ============================================== 아마존에서 최고의 Techalpine 책을 구입하십시오,en,전기 기술자 CT 밤나무 전기,en
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share