java——this关键字

核心概念:

利用this可以实现类属性的调用,类方法的调用,当前对象。

访问类中的属性必须加上this,明确标记本类的结构。

在调用普通方法时也都最好加上this

构造方法可以调用普通方法,普通方法不可以调用构造方法

public class Main {
    public static  void main(String args []) {
    Book book =new Book("java",29.9);
    System.out.println(book.getInfo());

    }
}

class Book{
    private String title;
    private Double price;
    public Book(){
        System.out.println("hhhhhhhh");
    }
    public Book(String title,Double price){
        this();      //调用本类的无参构造方法     此句只能放在构造方法的首行
        this.title=title;
        this.price=price;
    }
    public String getInfo(){
        return  "书名:"+this.title+"  价格:"+this.price;
    }
}

构造方法的相互调用:

class Book{
    private String empname;
    private String name;
    private Double sal;
    public Book(){
        this("无部门","无名",1000.0);
    }
    public Book(String empname){
        this(empname,"无名",10000.0);
    }
    public Book(String empname,String name){
        this(empname,name,10000.0);
    }
    public Book(String empname,String name,Double sal){
        this.empname=empname;
        this.name=name;
        this.sal=sal;
    }
    public String getInfo(){
        return "部门:"+empname+"/姓名:"+name+"/工资:"+sal;
    }
}

总结:

  • 类中属性要加上this;
  • 类中构造方法间相互调用,要保留出口;
  • this表示当前对象,指的是当前正在调用类中方法的对象,this不是一个固定的。

猜你喜欢

转载自blog.csdn.net/qq_36230524/article/details/89788634