Java 构造器或构造方法

构造方法的定义java

构造方法也叫构造器或者构造函数函数

构造方法与类名相同,没有返回值,连void都不能写this

构造方法能够重载(重载:方法名称相同,参数列表不一样)spa

若是一个类中没有构造方法,那么编译器会为类加上一个默认的构造方法。code

默认构造方法格式以下:对象

public 类名() {blog

}编译器

若是手动添加了构造器,那么默认构造器就会消失。编译

建议代码中将无参构造器写出来。class

public class Student {

    public String name;
    public int age;
    
    public void eat() {
        System.out.println("eat....");
    }
    
    //构造器
    /**
     * 名称与类名相同,没有返回值,不能写void
     * 构造器能够重载
     * 若是类中没有手动添加构造器,编译器会默认再添加一个无参构造器
     * 若是手动添加了构造器(不管什么形式),默认构造器就会消失
     */
    public Student() {
        System.out.println("无参构造器");
    }
    
    public Student(int a) {
        System.out.println("一个参数的构造器");
        age = 15;
    }
    
    public Student(int a, String s) {
        System.out.println("两个参数的构造器");
        age = a;
        name = s;
    }
}

 

构造方法的做用

构造方法在建立对象时调用,具体调用哪个由参数决定。

构造方法的做用是为正在建立的对象的成员变量赋初值。

public class Test {

    public static void main(String[] args) {
        
        //调用无参构造器
        Student s1 = new Student();
        //调用有参构造器
        Student s2 = new Student(15);
        System.out.println(s2.age);
        Student s3 = new Student(34, "小明");
        System.out.println(s3.name + ":" + s3.age);
    }

}

 

构造方法种this的使用

构造方法种能够使用this,表示刚刚建立的对象

构造方法种this可用于

  this访问对象属性

  this访问实例方法

  this在构造方法中调用重载的其余构造方法(要避免陷入死循环)

    只能位于第一行

    不会触发新对象的建立

public class Student {

    public String name;
    public int age;
    
    public void eat() {
        System.out.println("eat....");
    }
    //构造器
    //使用this()调用重载构造器不能同时相互调用,避免陷入死循环
    public Student() {
        //this()必须出如今构造器的第一行,不会建立新的对象
        this(15);//调用了具备int类型参数的构造器
        System.out.println("默认构造器");
    }
    public Student(int a) {
        this.eat();
        eat();//this.能够省略
    }
    //this在构造器中表示刚刚建立的对象
    public Student(int a, String s) {
        System.out.println("两个参数的构造器");
        this.age = a;
        this.name = s;
    }
}
public class Test {

    public static void main(String[] args) {
        Student s1 = new Student(15, "小明");
        System.out.println(s1.name + ":" + s1.age);
        Student s2 = new Student(12, "小红");
        System.out.println(s2.name + ":" + s2.age);
        
        Student s3 = new Student();
    }
}

 

概括this在实例方法和构造方法种的做用

this是java多态的体现之一

this只能够在构造方法和实例方法种存在,不能出如今static修饰的方法或代码块中

this在构造方法中表示刚刚建立的对象

this在实例方法种表示调用改方法的对象

this能够在实例方法和构造方法中访问对象属性和实例方法

this有时能够省略

this能够在实例方法中做为返回值

this能够看成实参

this可调用重载的构造方法

相关文章
相关标签/搜索