constructor

I am a beginner, but I summarized it for personal study

constructor

-Constructor is a kind of method for "pre-processing" to prepare the created instance before it is used by other instances.

3 rules

① Make the method name the same as ** class name ** ② ** Return type ** cannot be described ③ Can only be used with ** new ** (cannot be called except when creating an instance)

Private constructor

-By using private, the constructor can be made private (other classes cannot instantiate using new)

(Example) Class definition using a private constructor

Sample.java



public class Sample {
	private Sample() {
	}

	public static Sample getInstance() {
		return new Sample();
	}
}

-The private constructor prevents the external class from creating an instance, but there are two ways to get an instance (apparently, I don't understand yet). ① Hold the object in the static field ② Return the object with the static method

-Classes containing private constructors cannot be inherited

Default constructor

-If the constructor definition is omitted, the no-argument constructor that the compiler automatically adds at compile time is called ** default constructor **. -The default constructor is a constructor with ** no arguments and no processing **

Constructor overload

-Since the constructor can be defined freely, it is also possible to define multiple by ** overload **. -You can call the constructor of the same class by using ** this () **   ★ ** this () How to use ** -By using this () in ** in the constructor **, you can call other constructors defined in the same class. -Cannot be called unless the arguments (number of arguments, type, order) match

Recommended Posts

constructor
java (constructor)
[Scala] Constructor
Java constructor
Understand java constructor
Studying Java 8 (see constructor)
Upcast, Dowcast and Constructor
JAVA constructor call processing