# JAVA中的構造器與PHP中的構造函數是一模一樣的,所有都是一樣的
#
## 自己寫的構造器重載
## 構造器前面可以不加public
~~~
ackage com.msb2;
public class Person {
String name;
int age;
double height;
public Person(String name,int age,double height){ //構造器前面可以不加public
this.name=name;
this.age=age; //構造器賦值 this 代表正在創建的對象
this.height=height;
}
//方法:
public void eat(){
System.out.println("吃飯");
}
}
~~~
# 下面是老師的筆記:
#
```
package com.msb3.msb2;
/**
* @Auther: msb-zhaoss
*/
public class Person {
//屬性:
String name;
int age;
double height;
//空構造器
public Person(){
}
public Person(String name,int age,double height){
//當形參名字和屬性名字重名的時候,會出現就近原則:
//在要表示對象的屬性前加上this.來修飾 ,因為this代表的就是你創建的那個對象
this.name = name;
this.age = age;
this.height = height;
}
public Person(String a,int b){
name = a;
age = b;
}
//方法:
public void eat(){
System.out.println("我喜歡吃飯");
}
}
```
```
package com.msb3.msb2;
/**
* @Auther: msb-zhaoss
*/
public class Test {
//這是一個main方法,是程序的入口:
public static void main(String[] args) {
/*
1.一般保證空構造器的存在,空構造器中一般不會進行屬性的賦值操作
2.一般我們會重載構造器,在重載的構造器中進行屬性賦值操作
3.在重載構造器以后,假如空構造器忘寫了,系統也不會給你分配默認的空構造器了,那么你要調用的話就會出錯了。
4. 當形參名字和屬性名字重名的時候,會出現就近原則:
在要表示對象的屬性前加上this.來修飾 ,因為this代表的就是你創建的那個對象
*/
Person p = new Person();
/*p.age = 19;
p.name = "lili";
p.height = 180.4;*/
Person p2 = new Person("lili",19,180.4);
System.out.println(p2.age);
System.out.println(p2.height);
System.out.println(p2.name);
}
}
```