Table of Contents
Recursive constructor call
Constructor
Example 4
Output
in conclusion
Home Java javaTutorial Recursive constructor call in Java

Recursive constructor call in Java

Aug 27, 2023 pm 03:41 PM
Constructor recursion transfer

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
   }
}
Copy after login

Output

I am constructor
Copy after login

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");
   }
}
Copy after login

Output

Cart.java:4: error: recursive constructor invocation
Cart(String item, int price) { // constructor
   ^
1 error
Copy after login
The Chinese translation of

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");
   }
}
Copy after login

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)
Copy after login

We encountered a StackOverflowError error because creating an object inside a constructor results in an infinite loop of object creation.

The Chinese translation of

Example 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");
   }
}
Copy after login

Output

Constructor calling another Constructor
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Recursive implementation of C++ functions: Is there a limit to recursion depth? Recursive implementation of C++ functions: Is there a limit to recursion depth? Apr 23, 2024 am 09:30 AM

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.

Do C++ lambda expressions support recursion? Do C++ lambda expressions support recursion? Apr 17, 2024 pm 09:06 PM

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.

Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Apr 22, 2024 pm 03:18 PM

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.

Count the number of occurrences of a substring recursively in Java Count the number of occurrences of a substring recursively in Java Sep 17, 2023 pm 07:49 PM

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

C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application Apr 30, 2024 am 10:45 AM

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.

Detailed explanation of C++ function recursion: application of recursion in string processing Detailed explanation of C++ function recursion: application of recursion in string processing Apr 30, 2024 am 10:30 AM

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.

Detailed explanation of C++ function recursion: tail recursion optimization Detailed explanation of C++ function recursion: tail recursion optimization May 03, 2024 pm 04:42 PM

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 external resource access and calls in PHP development How to solve external resource access and calls in PHP development Oct 08, 2023 am 11:01 AM

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.

See all articles