Recursive constructor call in Java
Recursive constructor call is a compile-time error that occurs when a constructor calls itself. It's similar to recursion, where a method calls itself as many times as needed. A method that calls itself is called a recursive method, and a constructor that calls itself is called a recursive constructor.
In this article, we will learn about recursive constructor calling errors in Java through a few examples.
Recursive constructor call
Constructor
It is very similar to a method, but the difference is that methods define the behavior of objects, while constructors are used to initialize these objects. We can give the method any name we choose, but the constructor must be the same as the class name. Furthermore, methods can return a value, but constructors do not return any value because they cannot have any return type.
When the user does not create any constructor, the Java compiler will automatically create a constructor (we call it the default constructor).
Example 1
public class Cnst { // class name Cnst() { // constructor System.out.println("I am constructor"); } public static void main(String[] args) { Cnst obj = new Cnst(); // calling the Constructor } }
Output
I am constructor
Despite the similarities between constructors and methods, Java does not allow recursive constructors. This is a bad programming practice.
Example 2
The following example illustrates a recursive constructor call error.
Here we will create a class and define its constructor and two parameters. We will then call the same constructor inside its body.
public class Cart { String item; double price; Cart(String item, int price) { // constructor this(item, price); // constructor is calling itself // this keyword shows these variables belong to constructor this.item = item; this.price = price; } public static void main(String[] args) { Cart obj = new Cart("Bread", 15); // creating object System.out.println("Constructor calling another Constructor"); } }
Output
Cart.java:4: error: recursive constructor invocation Cart(String item, int price) { // constructor ^ 1 error
Example 3
is:Example 3
In the following example, we will try to define an object inside the constructor to check if Java allows creation of objects inside the constructor.
public class Cart { String item; double price; Cart(String item, int price) { // constructor // this keyword shows these variables belong to constructor this.item = item; this.price = price; Cart obj2 = new Cart("Milk", 55); // creating object } public static void main(String[] args) { Cart obj1 = new Cart("Bread", 15); // creating another object System.out.println("Constructor calling another Constructor"); } }
Output
Exception in thread "main" java.lang.StackOverflowError at Cart.<init>(Cart.java:9) at Cart.<init>(Cart.java:9) at Cart.<init>(Cart.java:9) at Cart.<init>(Cart.java:9) at Cart.<init>(Cart.java:9) at Cart.<init>(Cart.java:9) at Cart.<init>(Cart.java:9)
We encountered a StackOverflowError error because creating an object inside a constructor results in an infinite loop of object creation.
The Chinese translation ofExample 4
is:Example 4
The following example demonstrates that it is legal to call a constructor within another constructor.
public class Cart { // class String item; double price; Cart(String item, int price) { // first constructor // this keyword shows these variables belong to constructor this.item = item; this.price = price; } public Cart (int price) { // second constructor this(null, price); // calling the 1st constructor } public static void main(String[] args) { Cart obj = new Cart(15); // creating object System.out.println("Constructor calling another Constructor"); } }
Output
Constructor calling another Constructor
in conclusion
Java does not allow recursion of constructors, so this programming practice should obviously be avoided. In this article, we try to explain recursive constructors, starting with a discussion of constructors. Additionally, we found another error called StackOverflowError which was caused due to infinite loop.
The above is the detailed content of Recursive constructor call in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The recursion depth of C++ functions is limited, and exceeding this limit will result in a stack overflow error. The limit value varies between systems and compilers, but is usually between 1,000 and 10,000. Solutions include: 1. Tail recursion optimization; 2. Tail call; 3. Iterative implementation.

Yes, C++ Lambda expressions can support recursion by using std::function: Use std::function to capture a reference to a Lambda expression. With a captured reference, a Lambda expression can call itself recursively.

The recursive algorithm solves structured problems through function self-calling. The advantage is that it is simple and easy to understand, but the disadvantage is that it is less efficient and may cause stack overflow. The non-recursive algorithm avoids recursion by explicitly managing the stack data structure. The advantage is that it is more efficient and avoids the stack. Overflow, the disadvantage is that the code may be more complex. The choice of recursive or non-recursive depends on the problem and the specific constraints of the implementation.

Given two strings str_1 and str_2. The goal is to count the number of occurrences of substring str2 in string str1 using a recursive procedure. A recursive function is a function that calls itself within its definition. If str1 is "Iknowthatyouknowthatiknow" and str2 is "know" the number of occurrences is -3. Let us understand through examples. For example, input str1="TPisTPareTPamTP", str2="TP"; output Countofoccurrencesofasubstringrecursi

Tail recursion optimization (TRO) improves the efficiency of certain recursive calls. It converts tail-recursive calls into jump instructions and saves the context state in registers instead of on the stack, thereby eliminating extra calls and return operations to the stack and improving algorithm efficiency. Using TRO, we can optimize tail recursive functions (such as factorial calculations). By replacing the tail recursive call with a goto statement, the compiler will convert the goto jump into TRO and optimize the execution of the recursive algorithm.

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

Recursive definition and optimization: Recursive: A function calls itself internally to solve difficult problems that can be decomposed into smaller sub-problems. Tail recursion: The function performs all calculations before making a recursive call, which can be optimized into a loop. Tail recursion optimization condition: recursive call is the last operation. The recursive call parameters are the same as the original call parameters. Practical example: Calculate factorial: The auxiliary function factorial_helper implements tail recursion optimization, eliminates the call stack, and improves efficiency. Calculate Fibonacci numbers: The tail recursive function fibonacci_helper uses optimization to efficiently calculate Fibonacci numbers.

How to solve the problem of accessing and calling external resources in PHP development requires specific code examples. In PHP development, we often encounter situations where we need to access and call external resources, such as API interfaces, third-party libraries or other server resources. When dealing with these external resources, we need to consider how to access and call safely while ensuring performance and reliability. This article describes several common solutions and provides corresponding code examples. 1. Use the curl library to call external resources. Curl is a very powerful open source library.
