From simple things, I will output java steadily. I am studying with the goal of passing java silver.
A method that is always executed when instantiated Used for variable initialization, etc.
Qualifier constructor name(){
Processing content
}
The constellator name will be the same as the class name.
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 ~
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(){
}
}
This article was written with reference to the following information.
-Oracle Certification Textbook Java Programmer Silver SE11
Recommended Posts