java构造方法-this关键字的用法

  public class constructor {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Person p = new Person("张三",25,"山东");//构造函数的作用就是强制进行初始化,在进行赋值的时候如果有遗漏立即报错
		//如:Person p = new Person("张三",25);  会报错,提示少了一个赋值
		p.outPut();
	}
}
//this关键词在同一个类里面的方法去调用同一个类里的其他的方法时,this可以写也可以不写

//this可以看作变量,是对当前对象的引用/地址 class Person{ private String name; private int age; private String city; public Person(){//不带参数的显式构造方法(构造方法可以重载)
         System.out.println("无参构造方法");
    
     } public Person(String Name,int Age,String City){//带参数的显式构造方法
          this();//在一个构造方法里可以调用另一个构造方法,但是this();这句话必须放在构造方法的首句!! this.name = Name; this.age = Age; this.city = City; } //封装 public String getName(){ return name; } public void setName(String sName) { name = sName; } public int getAge(){ return age; } public void setAge(int sAge) { age = sAge; } public String getCity() { return city; } public void setCity(String sCity) { city = sCity; } public void outPut(){//输出 System.out.println("姓名:"+name+",年龄:"+age+",地址:"+city); } }

  

原文地址:https://www.cnblogs.com/liubing2018/p/8413566.html