栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Java 从零开始 4.7 this 关键字

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 从零开始 4.7 this 关键字

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

举个例子:

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

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

    
    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;

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

    
    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来指代引用名。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/269375.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号