Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an <init> method in Java? Can it be overridden? [duplicate]

<init> method can be found in stacktrace, for example. As I understood it represents initialization done in constructor.

If you try to execute

Object.class.getDeclaredMethod("<init>");

You'll get java.lang.NoSuchMethodException.

What is this method? When was it added to class? (in compilation - execution terms) Is it virtual, can one anyhow override it?

like image 445
Sergey Fedorov Avatar asked Dec 05 '13 17:12

Sergey Fedorov


People also ask

What is Init method in Java?

Init method is a predefined method to initialize an object after its creation. Init method is a life cycle method for servlets for java. It is started by the browser when java program is loaded and run by the browser. Init method is a predefine method to initialize an object after its creation. Read More.

What is the __ init __ method used for?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

What is __ init __ in Java?

Constructors. Python uses the fixed name __init__ for its constructor. Java has different notation: A method with the same name as the class, and no return value (not even void) is a constructor. Java constructors and instance methods headings do not include self like Python always has.

Is init a constructor in Java?

The init() method creates and loads the servlet. But the servlet instance is first created through the constructor (done by Servlet container). We cannot write constructors of a servlet class with arguments in servlet (It will throw Exception).


2 Answers

Have a look at the Java Virtual Machine Specification, chapter 2.9. It say on the <init> name:

At the level of the Java Virtual Machine, every constructor written in the Java programming language (JLS §8.8) appears as an instance initialization method that has the special name <init>. This name is supplied by a compiler. Because the name is not a valid identifier, it cannot be used directly in a program written in the Java programming language.

That's why <init> can be found on the stack trace, but is not accessible with code.

like image 72
Kai Sternad Avatar answered Oct 21 '22 07:10

Kai Sternad


What is an <init> method in Java?

It is a constructor. That's why you get a NoSuchMethodException when you try to call it as a method.

Can it be overriden?

No.


And if you see a <clinit> method, that is the classes static initialization "method".

like image 24
Stephen C Avatar answered Oct 21 '22 07:10

Stephen C