Introduction to Java (7)-Construction Method

Introduction to Java (7)-Construction Method

Table of contents

Introduction to Java (7)-Construction Method

Grammatical structures

Sample code


Grammatical structures

           - Constructor method
                [modifier list] Constructor method name (formal parameter list) {                     Constructor method body;                  }            - Syntax structure of ordinary method                 [modifier list] Return value type method name (formal parameter list) {                     Method body;                  }





      - The method name of the constructor must be consistent with the class name
      - "Return value type" cannot be added, and the default return value type is itself.
      - There is a return value after the constructor is executed, but there is no need to write the "return value"
      - Function: By calling the constructor, you can create an object
      - Call: new constructor name (actual parameter list)
      - When a class does not define any As for the constructor, the system will provide a parameterless constructor by default, that is, the default constructor
      - if there is a constructor defined, then the default constructor will not be provided. However, it is recommended to manually provide a parameterless constructor [frequently used]
      - The constructor supports overloading mechanism
      * Function:
           - Create an object
           - Initialize the memory space of the actual variable while creating the object

Sample code

class UserC {
	
	private String name;
	private int age;
	private String address;
	
	public UserC() {//无参数构造器
		
	}
	public UserC(int a) {//有参数构造器
		this.age=a;
		System.out.println(age);
	}
	public UserC(String b) {
		this.name=b;
		System.out.println(name);
	}
	public UserC(int d,String c) {
		this.name=c;
		this.age=d;
		System.out.println(name+"是"+age+"岁");
	}
	
	
	public String getName() {
		System.out.println(name);
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		System.out.println(age);
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getAddress() {
		System.out.println(address);
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
}


public class Constructor {
	
	public static void main(String[] arge) {
		UserC UserC1=new UserC();
		UserC UserC2=new UserC(16);//有参数构造方法的调用
		UserC UserC3=new UserC("张三");
		UserC UserC4=new UserC(24,"李四");
		//构造方法的重载机制
	}

}

Guess you like

Origin blog.csdn.net/qq_61562251/article/details/135046048