Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would anyone ever use the Java Thread no argument constructor?

In what situation would anyone ever use the no-argument constructor of the Java Thread class? The API says:

This constructor has the same effect as Thread(null, null, gname), where gname is a newly generated name.

Correct me if I am wrong, but I think the target of the thread can not be modified after the new Thread object is instantiated. If the target equals null then the start method will do nothing right?

Why would you use this constructor?

like image 275
Tamas Pataky Avatar asked Sep 27 '11 16:09

Tamas Pataky


People also ask

Why do we use no-arg constructor in Java?

In Java, a no-argument constructor is the default constructor and if you don't define explicitly in your program. Then Java Compiler will create a default constructor with no arguments. The purpose is to call the superclass constructor.

Why do we need no argument constructor?

The arguments of a constructor can only be found by type, not by name, so there is no way for the framework to reliably match properties to constructor args. Therefore, they require a no-arg constructor to create the object, then can use the setter methods to initialise the data.

Why does Hibernate require no argument constructor?

Though, In the case of Hibernate Persistent classes or Entities, it's must to provide a no argument constructor, so that Hibernate can create instance of Persistence classes, when you hibernate load them from database. It also uses newInstance() method to create instance of persistent classes.

How a no argument constructor is different from default constructor?

No-argument constructor: A constructor that has no parameter is known as the default constructor. If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class.


2 Answers

For one thing, it allows you to create subclasses without the PITA of explicitly calling the superclass constructor, e.g.

new Thread(){ 
   public void run() { ... }
}.start();
like image 175
Steve B. Avatar answered Sep 28 '22 00:09

Steve B.


If you make a (perhaps anonymou) class that inherits Thread and overrides run, your class needs to call this base constructor.

like image 23
SLaks Avatar answered Sep 28 '22 00:09

SLaks