[For beginners] Summary of java constructor

What is a constructor?

The constructor automatically passes information (fields) to the instance created by new.


public class Hero {
	String name;
	int hp;
}

Instantiating this Hero class will generate a Hero with no values (name is null and hp is 0).

public class Hero {
	String name;
	int hp;

	//constructor
	Hero(){
		this.name = "name";
		this.hp = 100;
	}
}

This allows you to assign values to fields. But with this, you can only make Hero with the same name and the same HP. I can't make a wizard HP50 or a fairy HP70. So I'll do this so that I can create characters freely.

public class Hero {
		String name;
		int hp;

		//constructor
		Hero(String name , int hp){
			this.name = name;
			this.hp = hp;
		}
}

What this does is that Hero (String name, int hp) takes name and hp and assigns them to the field. Where is it received from the main method?

public static void main(String[] args) {
		Hero h = new Hero("Brave" , 100);
	}

Since I set a constructor that receives two arguments in the Hero class, I set two arguments and call it when calling. If this is one argument, an error will occur.

The result is like this. Make sure the values are passed properly.

public static void main(String[] args) {
		Hero h = new Hero("Brave" , 100);
		System.out.println("Name is" + h.name + "is.");
		System.out.println("HP is" + h.hp + "is.");
	}

Result is

The name is brave.
HP is 100.

I was able to pass it properly.

But with this, if you want to pass only the name, you will get an error.


public class Main {

	public static void main(String[] args) {
		Hero h = new Hero("Brave");//Get an error
	}
}

In such a case, add a constructor to the Hero method.

public class Hero {
		String name;
		int hp;

		//constructor
		Hero(String name , int hp){   //First constructor
			this.name = name;
			this.hp = hp;
		}
		Hero(String name){   //Second constructor
			this.name = name;   
			this.hp = 50;
		}
}

You can set multiple constructors with the same name but with different numbers of arguments. This is called overloading. If new is called in the main method and the arguments are name and hp, the first constructor will be called. If there is only name in the argument, the second constructor will be called. This will not cause an error, but if more fields are passed, it will be less correctable and less readable. So


this()

Is used. You can use it to call a constructor in the same method.


public class Hero {
		String name;
		int hp;

		//constructor
		Hero(String name , int hp){   //First constructor
			this.name = name;
			this.hp = hp;
		}
		Hero(String name){   //Second constructor
			this(name , 50);
		}
}

It will be like this. We are calling the first constructor in the second constructor. The first constructor has two arguments, so this () has two arguments in (). The name will be the one passed from the main method, and the hp will not be passed, so enter any hp. Here, it is set to 50. When you run it with this

public class Main {

	public static void main(String[] args) {
		Hero h = new Hero("Brave");
		System.out.println("Name is" + h.name + "is.");
		System.out.println("HP is" + h.hp + "is.");
	}
}

result


The name is brave.
HP is 50.

You have been given 50 properly. This () is quite confusing. It's easier to understand if you write them one by one! You might think that, but then it will be difficult when you have to change the field later.

public class Hero {
		String name;
		int hp;

		//constructor
		Hero(String name , int hp){   //First constructor
			this.name = name;
			this.hp = hp;
		}
		Hero(String name){   //Second constructor
			this.name = name;   
			this.hp = 50;
		}
}

If you write like this and you have to change the field later


public class Hero {
		String name1;  //You have to change this to name1.
		int hp;

		//constructor
		Hero(String name , int hp){   //First constructor
			this.name = name;  //An error will occur.
			this.hp = hp;
		}
		Hero(String name){   //Second constructor
			this.name = name;  //An error will occur.
			this.hp = 50;
		}
}

In this case, you will have to fix two places. It's still good if there are two constructors, but as the number increases, the work becomes difficult. If you have fixed dozens of places, it is safe to make a mistake in one place.

It was the part I stumbled upon, so I summarized it. If you make a mistake, please point it out.

nkojima Thank you for pointing out. I deleted a part of the article. Certainly, when I read it back, it was different from readability. We will also refer to the article you sent.

Recommended Posts

[For beginners] Summary of java constructor
[Java] Summary of for statements
Summary of Java support 2018
A brief summary of Bootstrap features for beginners
Summary of Java environment settings for myself [mac]
A collection of simple questions for Java beginners
[Introduction to Java] Basics of java arithmetic (for beginners)
[Java] Beginner's understanding of Servlet-②
[Java11] Stream Summary -Advantages of Stream-
Java debug execution [for Java beginners]
[Java] Basic statement for beginners
[Java] Beginner's understanding of Servlet-①
[Java] Summary of regular expressions
[Java] Summary of operators (operator)
Object-oriented summary by beginners (Java)
Summary of Java language basics
Summary of Java Math class
Java for beginners, data hiding
[Java] Summary of control syntax
Java application for beginners: stream
Summary of java error processing
[Java] Summary of design patterns
[Java] Summary of mathematical operations
[For beginners] Quickly understand the basics of Java 8 Lambda
Introduction to Java for beginners Basic knowledge of Java language ①
List of frequently used Java instructions (for beginners and beginners)
Summary of file reading method for each Java file format
[For beginners] Explanation of classes, instances, and statics in Java
Summary of rails validation (for myself)
java (constructor)
Rock-paper-scissors game for beginners in Java
Java for beginners, expressions and operators 1
Summary of [Java silver study] package
[For beginners] Run Selenium in Java
Ruby on Rails for beginners! !! Summary of new posting functions
Java for beginners, expressions and operators 2
Java constructor
Generics of Kotlin for Java developers
Summary of object-oriented programming using Java
[For Java beginners] About exception handling
Classes and instances Java for beginners
Implementation of clone method for Java Record
[Java Silver] Summary of access modifier points
Summary of in-house newcomer study session [Java]
[java] Summary of how to handle char
Learn Java with "So What" [For beginners]
Summary of changes other than JEP of Java10
Summary of Docker understanding by beginners ② ~ docker-compose ~
[Java] Personal summary of conditional statements (basic)
[For beginners] Difference between Java and Kotlin
Rails [For beginners] Implementation of comment function
List of download destinations for oracle java
[Java] [Maven3] Summary of how to use Maven3
Features of spring framework for java developers
Explanation of Ruby on rails for beginners ①
Java Summary of frequently searched type conversions
[Java] Instance method, instance field, class method, class field, constructor summary
Summary of Java Math.random and import (Calendar)
Java knowledge summary
For JAVA learning (2018-03-16-01)
Java related summary