使用构造方法:
在使用new关键字创建对象时,系统会自动调用该对象的构造方法。构造函数的调用: new 构造函数();
定义构造方法的特点:
- 构造方法的名和类名相同,
- 构造方法没有返回值类型
构造方法的作用:
创建对象的,创建对象的同时,为属性赋初始值
当定义一个类的时候,系统会默认为该类提供一个无参数的构造函数,
如果程序中显示定义了类的构造函数,则默认的就不存在了
构造方法方式:
- 无参构造方法
- 有参构造方法
代码如下
public class Person {
public String name;
public int age;
public char sex ;
//有参构造方法
public Person(String name, int age, char sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
//有无构造方法
public Person() {
// TODO Auto-generated constructor stub
}
构造函数是可以实现重载
在创建对象时,根据传递的参数不同,会自动选择对应的构造方法。
代码如下
public class Student {
private String name;
private String school;
private int age;
private char sex ;
定义多个构造函数,实现构造函数的重载 由于定义了
public Student(String name) {
this.name = name;
}
public Student(String name, String school) {
this.name = name;
this.school = school;
}
public Student(String name, String school, int age) {
this.name = name;
this.school = school;
this.age = age;
}
public Student(String name, String school, int age, char sex) {
this.name = name;
this.school = school;
this.age = age;
this.sex = sex;
}
}
成员变量Vs. 局部变量作用域
当成员变量的作用域,与局部变量的作用域重合时,例如上图中的name和age。
局部变量会覆盖成员变量。所以,方法体中的name指的是形参name,而不是成员变量name。
我们通过编译器的颜色也能看的出来。
可以使用this关键字,解决问题:
调用构造函数:
public static void main(String[] args) {
//创建一个person对象,调用无参构造函数
Person person=new Person();
//创建一个person对象,调用有参构造函数,直接属性赋值了
Person person1=new Person("小明", 20,'男');
//已经通过构造函数为age ,name属性赋值了
person.age=17;
person.name="小黄";
}