Back To SchoolAmazon USBack-to-school picks: upgrade before the busy seasonAmazon US: study, desk and setup picks worth checking.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowBack To SchoolAmazon USStudy, work or desk setup? Compare useful picksAmazon US: study, desk and setup picks worth checking.See Picks×
Skip to content
THEGEEKSCLUB

What are Constructors in Java and Why Constructors are Used

java constructor program
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In our previous discussion on how to initialize instance variables in Java, we have came across constructor. Here we will discuss constructor in detail. First we will see what is constructor. It is very tedious to initialize all of the variables in a class each time an instance is created.

Even when you add convenience functions like initialize( ) [as we used in our previous examples], it would be simpler and more concise to have all of the setup done at the time the object is first created. Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor.

Constructor is a special type of method which has the same name as the class in which it resides and initializes the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately upon creation before the new operator completes and doesn’t have any return type because the implicit resource type of a class’ constructor is the class type itself.

Types of Constructors:

  1. Default Constructor.
  2. Parameterized Constructor.
  3. Copy Constructor. (Will discuss later)

Java Program

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;
  }
  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();
  }
}

Output

java constructor program

Explanation of the Java Code & Output

Employee() is a default constructor of Employee class in this code. It is called default because it doesn’t take any parameters. And when you do not explicitly define a constructor for a class, then Java creates a default constructor for the class. If you see the codes written in previous examples you will not find any constructors defined there, despite we were able to create object of those classes, this is because only for that reason.

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)

Flash on:

The default constructor automatically initializes all instance variables to zero.

Here in this example, object employee1 and employee3 is initialized with default constructor Employee()of Employee class. Here we have created the default constructor Employee() for Employee class and we are initializing the objects with some user defined values. Then it will no longer be initialized with zero as it is not implicit default constructor created by java. This is only done when no constructor is defined by programmer for that class. The default constructor automatically initializes all instance variables to zero.

Shopping ad
Sale
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

We have also written one parameterized constructor here. It takes parameters while object creation that’s why it is parameterized constructor. Employee object employee2 is initialized with parameterized constructor Employee (String empName, String addr, int ag, double sal).

Flash on:

Once you create your own parameterized constructor, then Java won’t create default constructor for that class. You have to explicitly create the default constructor for that class otherwise you will not be able to initialize objects using default constructor. It will throw a compile time error.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

Here if we didn’t create Employee() default constructor and meanwhile if we have created Employee(String empName, String addr, int ag, double sal) constructor, we will not be able to create object using Employee() constructor. i.e.

Employee employee1 = new Employee();

Employee employee3 = new Employee();   both these statements will no longer be valid.

Shopping ad
Sale
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

Now,  having removed Employee() default constructor if we compile then we will get this error during compile time.

java constructor program
Do let us know if you have any questions.

Next we will learn how to use copy constructors in Java.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

Checkout more useful tutorials and definitive guidelines on Java programming here.

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
Avatar photo
Written by

Nitin Agarwal

A blogger, tech evangelist, YouTube creator, books lover, traveler, thinker, and believer of minimalist lifestyle.

More from this author ↗
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

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.