Java 从零开始 4.7 this 关键字

this关键字的用法类似于python中的self,它可以替代引用名,指向对象本身。

举个例子:

public class Scores
{
    int maths;
    int English;
    int Chinese;

    /**
     * 我们给Scores类写一个构造方法
     */
    public Scores(){}//记得补上一个无参的构造方法
    public Scores(int maths, int English, int Chinese)
    {
        maths = maths;
       English = English;
       Chinese = Chinese;
    }

    /**
     * 我们给Scores类写一个打印的方法,输出里面的值
     */
    public void Scores_print()
    {
        System.out.println(maths);
        System.out.println(English);
        System.out.println(Chinese);
    }
}

然后在test中调用这个类:
 

public class test
{
	public static void main(String[] args)
	{
		Scores score = new Scores(120,130,140);
		score.Scores_print();
	}
}
 

结果如下:

可以看到结果为3个0,但是我们明明给了120/130/140三个数字进去,为什么结果会是3个0呢?

还记不记得前面说的,Java中遵循就近原则。

所以在语句:
 

        maths = maths;
       English = English;
       Chinese = Chinese;

执行的时候,是将构造方法的形参的值付给了形参自己,所以这三句语句等于什么都没有执行,而maths等成员变量的值没有被修改,为默认值0;

但是如果我们这么写test中的代码:
 

public class test
{
	public static void main(String[] args)
	{
		Scores score = new Scores();//使用无参的构造方法
		score.maths = 120;
		score.Chinese = 130;
		score.English = 140;
		score.Scores_print();

	}
}
 

结果如下:

可以看到成功将值付给了对象中的3个变量。

但是如果我们想用构造方法直接传入数值,应该怎么做呢?

我们可以这么改Scores中的代码:

public class Scores
{
    int maths;
    int English;
    int Chinese;

    /**
     * 我们给Scores类写一个构造方法
     */
    public Scores(){}//记得补上一个无参的构造方法
    public Scores(int maths, int English, int Chinese)
    {
        //在每个变量前加上this关键字
       this. maths = maths;
       this. English = English;
       this. Chinese = Chinese;
    }

    /**
     * 我们给Scores类写一个打印的方法,输出里面的值
     */
    public void Scores_print()
    {
        System.out.println(maths);
        System.out.println(English);
        System.out.println(Chinese);
    }
}

 然后将test中的代码改回原本的代码,结果如下

可以看到成功得到了结果

所以,this.其实替代了score.,也就是说,this和score这个引用名指向同一个地址,如果引用名改成别的什么比如说score2,那么this就和score2相同。

换句话说,this就相当于对象的引用名,只是在我们编写类的时候,并不知道用户会用取什么样的引用名。所以我们使用this来指代引用名。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值