Understand java constructor

Introduction

From simple things, I will output java steadily. I am studying with the goal of passing java silver.

What is a constructor?

A method that is always executed when instantiated Used for variable initialization, etc.

How to write

Qualifier constructor name(){
Processing content
}

The constellator name will be the same as the class name.

I will write

Main.java


class Cat {
	String name;
	int age;
	
	//constructor
	Cat() {
		System.out.println("It will be executed when new is done ~");
	}
}

public class Main {
	public static void main(String[] args) {
		Cat obj = new Cat();
	}
}

Execution result

It will be executed when new is done ~

The constructor is running correctly when new.

You can also pass arguments.

Main.java


class Cat {
	String name;
	int age;
	
	//constructor
	Cat(String msg) {
		System.out.println("It will be executed when new is done ~" + msg);
	}
}

public class Main {
	public static void main(String[] args) {
		Cat obj = new Cat("I'm rumbling ~");
	}
}

Execution result

It will be executed when it is new ~

in conclusion

If you do not define a constructor, the default constructor will be defined at compile time. It has no arguments and the implementation is empty.

class Cat {
  Cat(){
  }
}

References

This article was written with reference to the following information.

-Oracle Certification Textbook Java Programmer Silver SE11

Recommended Posts

Understand java constructor
java (constructor)
Java constructor
Understand Java 8 lambda expressions
Studying Java 8 (see constructor)
JAVA constructor call processing
Java
Java concurrency I don't understand
Java thread to understand loosely
I studied the constructor (java)
constructor
[For beginners] Summary of java constructor
[java8] To understand the Stream API
Java overload constructor starting from beginner
Java learning (0)
Studying Java ―― 3
[Java] array
[Java] Annotation
[Java] Module
Java array
Java tips, tips
Java methods
Java method
Java array
[Java] ArrayDeque
java (override)
java (method)
Java Day 2018
java (array)
Java static
Java serialization
JAVA paid
Java (set)
[Scala] Constructor
java shellsort
Studying Java -5
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Studying Java ―― 1
[Java] Array
[Java] Polymorphism
Studying Java # 0
Java review
java framework
Java features
Java features
Studying how to use the constructor (java)
java beginner 3
Java memo
java (encapsulation)
Java inheritance
[Java] Overload
Java basics
Decompile Java
[Java] Annotation
java notes
java beginner
Java (add2)
JAVA (Map)