Understanding Solidity Constructors: From Java Basics to Version‑Specific Pitfalls
This article compares Java and Solidity constructor concepts, shows how Solidity constructors were defined before and after version 0.4.22, demonstrates the required syntax changes with code examples, and explains the compilation warnings and errors that arise from version mismatches.
In object‑oriented languages like Java each class can have one or more constructors, and Solidity provides a similar feature.
Java Constructors
If a Java class does not declare a constructor, the compiler supplies a default one.
public class DemoTest {
}When a constructor is declared, object creation must use the declared form:
public class DemoTest {
public DemoTest() {
}
}Solidity Constructors (Pre‑0.4.22)
Older Solidity versions (< 0.4.22) used the contract name as a function to define a constructor.
pragma solidity ^0.4.21;
contract DemoTest {
}Explicit constructor using a function:
pragma solidity ^0.4.21;
contract DemoTest {
function DemoTest() public {
}
}Version‑Induced Deprecation
Compiling the above with Solidity 0.4.22 or later produces a warning:
Warning: Defining constructors as functions with the same name as the contract is deprecated. Use "constructor(...) { ... }" instead.From version 0.4.22 onward, the dedicated constructor keyword must be used.
Solidity Constructors (≥ 0.4.22)
pragma solidity ^0.4.22;
contract DemoTest {
constructor() public {
}
}If the newer syntax is compiled with an older compiler (e.g., 0.4.21), a parser error occurs:
ParserError: Expected identifier, got 'LParen'These mismatches are commonly seen when using development tools such as Remix or Truffle.
Summary
The article outlines how Solidity constructors evolved, provides side‑by‑side Java comparisons, shows the exact syntax for each Solidity version, and explains the warnings and errors that arise when the contract code and compiler version are inconsistent.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
