构造函数
一个特殊的方法
作用:用来为对象初始化信息(为对象的成员变量赋值)
使用:跟随new关键字使用
不需要返回值类型不需要void,可以使用return关键字,可以不使用
。
class Cat{
public String name;
public String type;
public String color;
//构造器
public Cat(){}
//构造器中的参数与成员同名问题
//就近原则
public Cat(String name){
this.name = name;
}
public Cat(String name,String type){
this.name = name;
this.type = type;
System.out.println(this);
}
public Cat(String name,String type,String color){
//调用奔雷中的其他构造器为name,与type成员变量赋值,因为已经有其他构造器实现了赋值需求,直接调用即可
this(name,type);
this.color = color;
}
Java基础类和对象:this
this代表当前对象的意思,this是讲本类里属性的引用指向参数的应用。
构造器首行,通过this(实参)调用本地的其他构造器。
public class ThisDemo {
//重载构造器
public ThisDemo(){
//调用本类中的其他构造器
this(false);
System.out.println("空构造");
}
public ThisDemo(int i){
System.out.println("一个int类型参数构造器"+i);
}
public ThisDemo(boolean flag){
//this();
System.out.println("一个boolean类型参数构造器"+flag);
}
区分同名变量问题—>局部变量与成员变量的同名问题:
在构造器中:
默认就近原则。
局部变量–>方法的形参,方法内部自定义的局部变量同名时:this.成员变量=局部变量。
this指代当前new的对象,在new某一个对象的时候,才会调用执行的构造器的初始化信息,this就指代那一个对象。
public class This {
String name ;
String id;
public This(String name, String id) {
this.name = name;
this.id = id;
}
public static void main(String[] args) {
This t=new This("名字","id");
}
}
在方法中:
存在方法中的局部变量与成员变量同名的时候依旧是通过 this.成员变量。
在成员方法中this指代调用成员方法的对象。
当没有同名问题时候,指代成员时候,默认省略this。
public class This {
String name ;
String id;
public void ahO(){
System.out.println(this.name+id);
}
public static void main(String[] args) {
This t=new This();
t.name="名字";
t.id="id";
t.ahO();
}
}
运行结果: