java构造方法的不同

时间:2022-02-01 07:40:07

分为有参数和无参数,还有THIS的使用方法,可用于传递给类,也可用于调用其它构造方法。

public class Book {
    private String name;
    public Book(){
        this("this调用有参数的构造方法");
        System.out.println("无参数的构造方法。");
    }
    public Book(String name){
        System.out.println("有参数构造方法。");
        this.name = name;
        //System.out.println("传入类的形参name:" + name);
    }
    public String getName(){
        int id = 0;
        //setName("Java");
        return id + this.name;
    }
    public void setName(String name){
        this.name = name;
    }
    public Book getBook(){
        return this;
    }

}
import java.util.Arrays;

public class HelloJava {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println();
        Book abook = new Book("First Pamram");
        abook.setName("This name is import.");
        String astring = abook.getName();
        System.out.println(astring);
        Book bbook = new Book();

    }
}

java构造方法的不同