this关键字

1、this关键字可以访问当前类中的属性(也叫成员变量或实例变量)

     如:this.id   表示当前这个对象的id属性

2、this关键字可以访问当前类中的方法(也叫成员方法或实例方法)

    如:dispaly();  等价于this.display();

   注意:1)如果在同一个类中访问成员(成员变量和成员方法),并且成员没有使用static修饰,则默认前面添加this关键字。

              2)在同一个类中,局部变量和成员变量可以同名,但是局部变量优先,如果非要访问成员变量,则必须添加this关键字。

3、this关键字可以访问当前类中的构造方法,如下:

     this();

     this(brand,price);

    注意:1)如果使用this关键字访问构造方法,则必须编写在构造方法中,并且放在第一行

 

代码分享:

class Computer{
    //成员变量
    String id;
    String brand;
    double price;
    String color;

    //构造方法
    public Computer(String brand,double price){
        this.brand=brand;
        this.price=price;
        System.out.println("brand:::"+brand);
        System.out.println("price:::"+price);
    }

    public Computer(String id,String brand,double price,String color){
        this(brand,price);
        //如果使用this关键字访问构造方法,则必须编写在构造方法中,并且放在第一行。
        this.id=id;
        this.color=color;
    }
    //如果在同一个类中访问成员(成员变量和成员方法),并且成员没有使用static修饰,则默认前面添加this关键字。
    //同一个类中的属性和方法是直接方法
    public void show(){
        System.out.println("电脑信息show如下:");
        System.out.println("id]:"+id);
        System.out.println("brand]:"+brand);
        System.out.println("price]:"+price);

        display();
        System.out.println("--------");
        this.display();//dispaly();  等价于this.display();
        System.out.println("---------");
    }

    public void display(){
        System.out.println("电脑信息display如下:");
        System.out.println("id}:"+this.id);//this代表当前这个对象
        System.out.println("brand}:"+this.brand);
        System.out.println("price}:"+this.price);
        System.out.println("color}:"+this.color);
    }
}





public class ThisTest {
    public static void main(String[] args){
        Computer c=new Computer("001","Lenovo",90,"银色");
        c.show();
        //c.display();
        
    }
}

               

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值