Java Constructor summary

Constructor structure

The method name as a class structure:
class name (parameter list []) {

}
Using new call, the following sample code (not contain constructors)

public class UserInfo {
	public static void main(String[] args) {
		UserInfo Lin = new UserInfo();
	}
}

Constructor Features

a. constructor must not have a return value portion, and the void can not.
B. Have a default class constructor parameters when defining a parameter of the constructor, the default constructor with no arguments hide.
C. The method of construction does not allow the use of final, static and other modifications. If there is final, static, etc., code compilation error occurs, you can not run.
D. define a plurality of class constructors needed, which is reflected overloaded.
. e class constructor may call each other, i.e. this (argument list); it must be placed in the first row of the code configuration method is effective, while this method will only be a predetermined method called once.
Detailed code is as follows:


public class UserInfo {

	int age;
	String name;
	String moble;
	String address;
	
	UserInfo(int a,String n,String m,String add){
		this (18,"lindazhi");
		age = a;
		name = n;
		moble = m;
		address = add;
	}
	
	UserInfo(int a,String n){
		age = a;
		name = n;
		System.out.println(a);
		System.out.println(n);
	}
	public static void main(String[] args) {
		UserInfo Lin = new UserInfo (12,"林扬","857857857","河南省郑州市");
		System.out.println(Lin.age);
		System.out.println(Lin.name);
		System.out.println(Lin.moble);
		System.out.println(Lin.address);
	}
}

And there is no argument constructor argument constructor

Constructor with no arguments:

public class UserInfo {
	int age;
	String name;
	String moble;
	String address;
	
	UserInfo(int a,String n){
		age = a;
		name = n;
		System.out.println(a);
		System.out.println(n);
	}
	public static void main(String[] args) {
		UserInfo Lin = new UserInfo();
		Lin.age = 18;
		Lin.name = "林杨";
		Lin.number = "857857857";
		Lin.address = "河南省郑州市";
		System.out.println(Lin.age);
		System.out.println(Lin.name);
		System.out.println(Lin.number);
		System.out.println(Lin.address);
	}
}

There arg constructor:

public class UserInfo {
	int age;
	String name;
	String moble;
	String address;
	
	UserInfo(int a,String n,String m,String add){
		this (18,"lindazhi");
		age = a;
		name = n;
		moble = m;
		address = add;
		public static void main(String[] args) {
		UserInfo Lin = new UserInfo (12,"林扬","857857857","河南省郑州市");
		System.out.println(userInfo.age);
		System.out.println(userInfo.name);
		System.out.println(userInfo.number);
		System.out.println(userInfo.address);
	}
}

This can be seen: there is a reference member configured to more easily assign values ​​to variables.

Published 19 original articles · won praise 0 · Views 468

Guess you like

Origin blog.csdn.net/zzu957/article/details/104579855