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.

 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

最新文章

  1. redis 基本数据类型
  2. U-Mail反垃圾邮件网关过滤Locky勒索邮件
  3. BZOJ4386 : [POI2015]Wycieczki
  4. Android学习笔记之打钩显示输入的密码
  5. python计算文件的行数和读取某一行内容的实现方法
  6. Android Activity初探
  7. 【android-cocos2d-X 环境配置】在Mac下搭建Cocos2d-X-android开发环境!
  8. SQL的四种语言和数据库范式
  9. memcpy函数的使用方法
  10. Memcache Slab Eviction 功能测试
  11. How to solve java.net.SocketTimeoutException:60000millis problem in HDFS
  12. java数据类型,hibernate数据类型,标准sql数据类型之间的对应表
  13. 深入 HTML5 Web Worker 应用实践:多线程编程
  14. Mysql基本命令一
  15. ORM之轻量级框架--Dapper
  16. 64bit program invoke 32bit library with rpcgen
  17. 2019-1-17 script(1)
  18. 一篇文章有若干行,以空行作为输入结束的条件。统计一篇文章中单词the(不管大小写,单词the是由空格隔开的)的个数。
  19. 19 模块之shelve xml haslib configparser
  20. Flash:移除匿名函数监听器EventListener

热门文章

  1. back_inserter的用法
  2. 70个经典的 Shell 脚本面试问题
  3. Ubuntu下访问SSH
  4. [转]Spring Boot——2分钟构建spring web mvc REST风格HelloWorld
  5. 利用扩展双屏技术及Chrome浏览器,高速剖析优秀网页Div及CSS构成,并高效实现原型创作
  6. Oracle用户解锁的三种办法及默认的用户与密码
  7. gulp入门学习实例
  8. AngularJs练习Demo4
  9. 读取并解析properties文件
  10. String new赋值、直接赋值