• Copy Constructor in Java


    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.

     1 class Complex {
     2  
     3     private double re, im;
     4      
     5     // A normal parametrized constructor 
     6     public Complex(double re, double im) {
     7         this.re = re;
     8         this.im = im;
     9     }
    10      
    11     // copy constructor
    12     Complex(Complex c) {
    13         System.out.println("Copy constructor called");
    14         re = c.re;
    15         im = c.im;
    16     }
    17       
    18     // Overriding the toString of Object class
    19     @Override
    20     public String toString() {
    21         return "(" + re + " + " + im + "i)";
    22     }
    23 }
    24  
    25 public class Main {
    26  
    27     public static void main(String[] args) {
    28         Complex c1 = new Complex(10, 15);
    29          
    30         // Following involves a copy constructor call
    31         Complex c2 = new Complex(c1);   
    32  
    33         // Note that following doesn't involve a copy constructor call as 
    34         // non-primitive variables are just references.
    35         Complex c3 = c2;   
    36  
    37         System.out.println(c2); // toString() of c2 is called here
    38     }
    39 }

    Output:

    Copy constructor

    called (10.0 + 15.0i)

     1 class Complex {
     2  
     3     private double re, im;
     4  
     5     public Complex(double re, double im) {
     6         this.re = re;
     7         this.im = im;
     8     }
     9 }
    10  
    11 public class Main {
    12      
    13     public static void main(String[] args) {
    14         Complex c1 = new Complex(10, 15);  
    15         Complex c2 = new Complex(c1);  // compiler error here
    16     }
    17 }

    Compile error

  • 相关阅读:
    java基础学习总结——方法的重载(overload)
    java基础学习总结——哈希编码
    HDFS常用命令总结
    统计列表中有重复的元素
    url编解码
    python读取文件指定行内容
    python对接elasticsearch的基本操作
    爬虫速度太慢?来试试用异步协程提速吧!
    Python多线程的事件监控
    Python只有文件不存在才能写文件
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4941395.html
Copyright © 2020-2023  润新知