Site icon TestingDocs.com

Java Constructors

Overview

Let’s learn about Java constructors in this tutorial. Constructors are invoked by the JVM automatically when the object is created. A constructor is called by the new operator.

Constructor declaration has the same name as the class name and has 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 :

https://www.oracle.com/java/

Exit mobile version