Java Constructors
Overview
In this tutorial, we will learn about Java constructors. Constructors are special methods that have the same name as the Java class. The JVM invokes constructors automatically when an object is created. The new operator invokes a constructor.
The constructor declaration has the same name as the class name but no return type. The constructor never returns any value to the JVM. Constructors may or may not have arguments. When a class doesn’t have a constructor defined, the Java compiler automatically creates a default no-argument constructor. A Java class can have multiple constructors defined.
Example
The basic purpose of the constructor is to initialize the instance variables of the class. Let’s look at an example to illustrate the concept.
/* * Java Constructors Demo Program * Java Tutorials - www.TestingDocs.com */ public class Book { private String author; private String title; private double price; //no-arg constructor public Book() { } // Constructor with arguments public Book(String a, String t, double p) { this.author = a; this.title = t; this.price = p; } //setters & getters public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String t) { this.title = t; } public double getPrice() { return price; } public void setPrice(double p) { this.price = p; } @Override public String toString() { return "Book Details --\nAuthor= " + author + "\nTitle=" + title + "\nPrice=$ " + price; } }
Let’s create an object with sample data using the new operator. The constructor with arguments will be invoked.
/* * Driver Program to Test code * Java Tutorials - www.TestingDocs.com */ public class TestBook { public static void main(String[] args) { //Create Book Object - new operator invokes Book constructor Book novel = new Book("Ernest Hemingway","The Old Man and the Sea",9.99); System.out.println(novel.toString()); } }
Sample Output
Book Details —
Author= Ernest Hemingway
Title=The Old Man and the Sea
Price=$ 9.99
We can automatically create generate constructors for the class using the IDE tools like Eclipse, IntelliJ IDEA, and NetBeans IDE.
https://www.testingdocs.com/generating-constructors-in-eclipse-ide/
—
Java Tutorials
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :