Copy Constructor in Java
2015-11-06 03:06
267 查看
Reference: TutorialPoints, GeekforGeeks
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to:
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
In C++, if a copy constructor is not defined in a class, the compiler itself defines one.
Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.
Output:
Copy constructor
called (10.0 + 15.0i)
Compile error
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to:
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
In C++, if a copy constructor is not defined in a class, the compiler itself defines one.
Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.
class Complex { private double re, im; // A normal parametrized constructor public Complex(double re, double im) { this.re = re; this.im = im; } // copy constructor Complex(Complex c) { System.out.println("Copy constructor called"); re = c.re; im = c.im; } // Overriding the toString of Object class @Override public String toString() { return "(" + re + " + " + im + "i)"; } } public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy constructor call Complex c2 = new Complex(c1); // Note that following doesn't involve a copy constructor call as // non-primitive variables are just references. Complex c3 = c2; System.out.println(c2); // toString() of c2 is called here } }
Output:
Copy constructor
called (10.0 + 15.0i)
class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; } } public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); Complex c2 = new Complex(c1); // compiler error here } }
Compile error
相关文章推荐
- Java基础语法2
- Java基础语法1
- Java容器学习笔记(1)
- 10003---JavaWeb开发基础--Servlet
- adt eclipse打开预览android XML布局很卡
- struts2的认识
- JAVA概述
- 编写供有限状态机使用的Java框架
- eclipse创建android项目,XML文件无法正常可视化预览布局
- spring3.2 aop 搭建 (1)
- java中的多线程
- Java enum的用法详解
- java.io包的总体框架图, 便于记忆!
- Java IO框架
- Struts2+ajax之form表单提交实例
- Java性能调优
- JAVA文档注释
- 递归练习----递归输出某个目录下的.java文件
- java对象中的表面类型与实际类型
- java之行——第一天