Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversCord CheckAmazon USReplace worn cables before they cause problemsCompare durable charging cables and adapters that hold up to daily commuting and travel.See PicksPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
THEGEEKSCLUB

Java Tutorial: Copy Constructor in Java

create multilevel hierarchy Java
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In our previous discussion, we have come to know how to pass an object reference to a method. In the same way, we can pass the reference to a constructor to initialize the instance variables of another object of the same class. You can use the same value of the instance variables of the object which is sent to the constructor. One object is copied to other objects. Let’s check out this Java Tutorial Copy Constructor in Java language.

Java Tutorial Copy Constructor in Java

  • Advantages of using Copy Constructor
  • Disadvantages of using Copy Constructor
  • Program for Copy Constructor
  • Explanation of the Java Code & Output

Advantages of using Copy Constructor

There are several use cases where Copy Constructors works well with respect to other constructors in Java.

As we know, objects can be cloned in Java using the clone() method. But copying object using clone() is not flexible and extensible, doesn’t work fine as well.

The first problem is that no constructor call happens when the object is being cloned. As a result, it is your responsibility, as a writer of the clone method, to make sure all the members have been appropriately set. Here is an example of where things could go wrong.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Shopping ad
Sale
FYY Electronic Organizer, Travel Tech Pouch Bag, Cable Organizer Black
  • Dimensions: 7.5" x 4.3" x 2.2". Compact size and lightweight make it easy to carry and put into your backpack, handbags or laptop bag without taking much space. Suitable for family use and daily organization. Note: Small mesh pockets are ideal for charging cords no longer than 3ft; longer cables (over 3ft) fit better in the larger compartments
  • Quality Material: This electronic organizer travel case made of high quality durable waterproof oxford and soft sponge inside to secure your gadgets in place and deliver a quick access whenever you want. Water-resistant fabric protects your gear from unexpected splashes, keeping all your electronic essentials safe and secure
  • Double Layers Design: This tech pouch features a double-layer interior design with 8 compartments, including multiple see-through mesh pockets and ample space to store your cords, cables, USB drives, cellphone, charger, mouse, flash drive and more, keeping all accessories neatly organized and tangle-free
  • Practical and Convenient: Comes with a comfortable hand strap for easy carrying; You may carry it in your hand when heading out. Durable and smooth zipper closure keeps your favorite device securely, convenient for you to have quick access to the items inside the case
  • Portable and Lightweight: The small size and lightweight design durable cable organizer pouch is a perfect choice when going on holiday, business trip, travel, office. Enjoy hassle-free travel without wasting time on tangled accessories. Great gift for yourself also a nice share with families and friends. (No include cords, electronic accessories)

Consider a class keeping track of the total number of objects of that type, using a static int member. In the constructors you would increase the count. However, if you clone the object, since no constructor is called, the count will not truly reflect the number of objects!

Further, if the class has final fields, these can’t be given a value in the clone method. It leads to problems with properly initializing the object’s last fields. If the final field is referring to some internal state of the object, then the cloned object ends up sharing the internal state, and this surely is not correct for mutable objects.

Shopping ad
Ordilend Keyboard Cleaner & Laptop Cleaning Kit, All-in-1 for Computer PC
  • 【UPGRADED LAPTOP CLEANING KIT 】 The macbook cleaning kit computer screen cleaner comes with a number of accessories including a retractable large brush, polishing cleaning cloth X 2, keycap puller, metal pen tip, flocking sponge, thin soft brush, soft plastic lens cleaning pen, 5 replacing cloth, large cleaning microfiber cloth. You deserve the comprehensive computer cleaning kit keyboard vacuum at a low cost
  • 【PROFESSIONAL KEYBOARD CLEANING KIT】 The laptop screen cleaner keyboard cleaner can pull out the keycaps of gaming keyboards and mechanical keyboards. A retractable keyboard brush works on laptops and keyboards, while the mini high-density brush is great for deep cleaning between keys for cleaning between flatter keys on a laptop, the metal pin tip gently removes any stains. This electronic cleaning kit macbook cleaner totally meets professional cleaning needs
  • 【OFFICE DESK ACCESSORIES】This keyboard cleaner kit is easy to use and can clean your keyboard and electronic screen with just one swipe. Wiping with the 2mm thicken widen polishing cleaning cloth designed at a right angle for better fitting screen corners of computers with our recyclable cleaning spray, The laptop cleaner kit for macbook effectively absorbs stubborn stains, leaves no discoloration, no streaks, and no fiber shedding on the screens
  • 【MULTIFUNCTIONAL TOOLS 】Mini soft brush and soft plastic lens cleaning pen are specially designed for DSLR camera screen, lens, and other delicate surfaces. 5 more cleaning cloths of it supplied for replacement. The flocking sponge is an excellent tool for cleaning earbuds charging cases, And the earbud cleaning kit is ideal. This electronics for college students is equivalent to 10 other electronic cleaning kit
  • 【PORTABLE DESIGN & CLEANER TOOL】 The office supplies is compact in design, easy to carry, and you can easily take it anywhere. It's convenient to keep one in a drawer, one in your car, or in your bag and dorm. It is easy to use and can clean your keyboard and electronic screen with just one swipe. Is the college essentials cleaning tool for your friends, family, colleagues and students

Disadvantages of using Copy Constructor in Java

As one object is the replica of another, any change in the first one it will inadvertently change the values of the instance variables of other. So you have to be careful and better not to declare copy constructor as public. Otherwise, during inheritance, it doesn’t satisfy the Open-Closed Principle (OCP). The OCP, by Bertrand Meyer, states that software entities should be open for extension, but closed for modifications.

Program for Copy Constructor

class Employee{
  String employeeName;
  String address;
  int age;
  double salary;

/*Default Constructor */

  Employee(){
    employeeName = "Platini";
    address = "France";
    age = 45;
    salary = 120500.92;
  }

/* Parameterized Constructor */

  Employee(String empName,String addr,int ag,double sal){
    employeeName = empName;
    address = addr;
    age = ag;
    salary = sal;
  }

/* Copy Constructor  */

  Employee(Employee emp){
    employeeName = emp.employeeName;
    address = emp.address;
    age = emp.age;
    salary = emp.salary;
  }

  void showDetails(){
    System.out.println("Employee's Name: "+employeeName);
    System.out.println("Employee's Address: "+address);
    System.out.println("Employee's Age: "+age);
    System.out.println("Employee's Salary: "+salary);
  }

}

class ConstructorDemo{
  public static void main(String args[]){
    System.out.println("Employee Details");
    System.out.println("----------------");
    Employee employee1 = new Employee();
    employee1.showDetails();

    System.out.println("----------------");

    String employeeName = "John";
    String address = "Los Angles";
    int age = 25;
    double salary = 34503.92;
    Employee employee2 = new Employee(employeeName,address,age,salary);
    employee2.showDetails();

    System.out.println("----------------");

    Employee employee3 = new Employee();
    employee3.showDetails();

    System.out.println("----------------");

    Employee employee4 = new Employee(employee2);
    employee4.showDetails();

    System.out.println("----------------");

    Employee employee5 = new Employee(employee3);
    employee5.showDetails();

  }
}

Output

Java Tutorial Copy Constructor in Java

Explanation of the Java Code & Output

Please carefully observe the code marked in red, basically, in the Employee class, you will find the syntax on how to declare copy constructor. We have created two more objects employee 4 and employee5 which are a copy of employee2 and employee3 respectively. From the output, it is visible that instance variables of employee4 have the same value as the values of instance variables of employee2. Same is true for employee5.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Shopping ad
Sale
BAGSMART Large Electronic Organizer Travel Case for Tech Accessories, Black
  • Compatible Space: This electronics organizer bag features 2 zippered mesh pockets fits phones, standard power banks, 4 elastic loop pouches for small items, 2 elastic loop pouches for wireless headphones and small chargers. Elastic loops for phone charging cable. And specific slots for SD cards. Please check the size to ensure it meets your needs
  • Lightweight Travel Accessories: The size of the electronic organizer travel case is 10.6" L x 7.5" W x 1.2" H, Compact but substantial size fits your intended bag or space. Suitable for traveling use and daily organization
  • Keep Everything Organized: This compact travel organizer features dedicated compartments for your phone charger, cables, and tech accessories, keeping them tangle-free and ready to go. You can find travel accessories quickly, no chasing cords in your pack anymore
  • Durable Travel Essentials: Features double zippers for easy access, elastic loops with non-slip grips for daily protection. Organizer for office use and traveling, (Not including cords, electronic accessories). It can serve as a travel checklist. Before you leave a place, just open the case and check if everything is there, preventing you from leaving things behind
  • Versatile Use: Its practicality and convenience make it a travel essential bag. It is suitable for a weekend trip, business trip, and travel. This organizer pouch is suitable for office, business, daily use and can be given as a gift for friends, family, or men, for birthdays, Valentine's Day, Christmas Day, Father's Day

Next, we will see how to use the keyword “static” in Java. Check out more useful tutorials and final guidelines on Java programming here.

Shopping ad
Sale
HOTO Pocket-Size Laser Measuring Tool, EDC Gadget Birthday Gift for Men Dad
  • Award-Winning Compact Design & EDC-Ready Gift Choice: Weighing only 0.09 lb and sized like a credit card, this compact laser measure is designed for everyday carry. It slips easily into a pocket, tool pouch, or bag, and can attach to a keychain for quick access wherever you go. Its minimalist design, premium tactile finish, and practical one-button measuring make it a useful EDC gadget for DIYers, real estate agents, homeowners, and tech enthusiasts. A thoughtful gift for men on any occasion
  • One-Button Easy Measuring, Simple to Use: Designed with simple one-button operation, this compact laser tape measure makes quick measuring easy without complicated controls. Just press to measure room dimensions, furniture spacing, window height, wall décor placement, and everyday distances around the home. Ideal for users who want a smart, pocket-size measuring tool that fits naturally into an everyday carry (EDC) setup and feels intuitive, modern, and easy to use
  • Fast & Accurate Indoor Measurements with Class 2 Laser: Measure distances from 0.16 ft to 98 ft with up to ±1/16 in / ±2 mm accuracy. With quick measurement response in about 0.2 seconds, HOTO helps you check spaces efficiently for home renovation, furniture layout, moving, decorating, craft projects, and DIY planning. Built with a Class 2 laser for everyday indoor measuring; use as directed and avoid direct eye exposure
  • Low-Power OLED Display & USB-C Rechargeable Convenience: The low-power OLED display provides clear indoor readings while helping reduce battery drain. With USB-C rechargeable design, auto shut-off, and up to 1000 measurements per charge, this digital laser measure is built for repeated daily use without frequent battery replacement. Compact enough to keep in a drawer, toolbox, bag, or pocket
  • Useful for Home, Work & Everyday Projects: From home renovation and furniture measuring to room planning, real estate checks, interior design, and light construction projects, this pocket-size laser distance measure is made for practical everyday use. Compact enough to keep in a drawer, toolbox, bag, or pocket, it is a stylish measuring tool that feels just as giftable as it is useful
Shopping ad
ColorCoral Cleaning Gel Universal Dust Cleaner for PC Keyboard Car Detailing Office Electronics Laptop Dusting Kit Computer Dust Remover, Computer Gaming Car Accessories, Gift for Men Women 160g
  • Universal fit: ColorCoral cleaning gel, simple and convenient cleaning kits for PC/laptop keyboard and other rugged surface, such as the car vent, camera, printer, telephone, calculator, Instrument, speaker, air conditioner, TV and other appliances
  • Safe cleaning gel: The keyboard cleaner gel is made from natural gel, no sticky to hands, smells sweet with lemon fragrance, no stimulation to skin
  • Easy dust cleaning: Make sure your hands are dry and clean, knead the cleaning gel into a ball, press the cleaning gel slowly into the keyboard, car vent and rugged surface till the cleaning gel could touch the bottom and then pull out, the dust would be carried away with the cleaning gel
  • Reusable: The keyboard cleaning gel could be used repeatedly till the color turn to dark or it become sticky, then you have to replace the cleaning gel with a new one. After cleaning, please stock the cleaning gel in cool place. (Note: Don’t wash the gel in water.)
  • In the package: 1 can of universal cleaning gel, we provide the cleaning gel with brand new, if you find the package broken, the cleaning gel dirty, or any other quality issues, please email us through message, we provide you new one soon

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi
William johnson
Written by

William Johnson

William graduated with a B.S. in Information Systems and later completed a certificate program in narrative nonfiction. He has 12 years in service journalism and digital publishing, with a track record of turning complex research into daily guidance.

More from this author ↗
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.