Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Constructor (object-oriented programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Java === In [[Java (programming language)|Java]], constructors differ from other methods in that: * Constructors never have an explicit return type. * Constructors cannot be directly invoked (the keyword β<code>new</code>β invokes them). * Constructors should not have non-access modifiers. Java constructors perform the following tasks in the following order: # Call the default constructor of the superclass if no constructor is defined. # Initialize member variables to the specified values. # Executes the body of the constructor. Java permit users to call one constructor in another constructor using <code>this()</code> keyword. But <code>this()</code> must be first statement. <ref>{{Cite web|url=https://ranjeetkumarmaurya.wordpress.com/2017/02/06/constructor-in-java/|title=Details on Constructor in java}}</ref> <syntaxhighlight lang="java"> class Example { Example() // Non-parameterized constructor { this(1); // Calling of constructor System.out.println("0-arg-cons"); } Example(int a) // Parameterized constructor { System.out.println("1-arg-cons"); } } public static void main(String[] args) { Example e = new Example(); } </syntaxhighlight> Java provides access to the [[superclass (computer science)|superclass's]] constructor through the <code>super</code> keyword. <syntaxhighlight lang="java"> public class Example { // Definition of the constructor. public Example() { this(1); } // Overloading a constructor public Example(int input) { data = input; // This is an assignment } // Declaration of instance variable(s). private int data; } </syntaxhighlight> <syntaxhighlight lang="java"> // Code somewhere else // Instantiating an object with the above constructor Example e = new Example(42); </syntaxhighlight> A constructor taking zero number of arguments is called a "no-arguments" or "no-arg" constructor.<ref>{{cite web|url=http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html|title= Providing Constructors for Your Classes |publisher=Oracle Corporation|date=2013|access-date=2013-12-20}}</ref>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)