JAVA(8)—this关键字

这里写目录标题

0x01 介绍

this关键字指向的是当前对象的引用。

0x02 作用

  • 调用此方法的对象的引用
  • this 可以看作一个变量,它的值是当前对象的引用
  • this可以处理方法中函数成员变量与形参同名的问题
  • 在方法中需要调用方法的对象时,可以使用this
  • 构造方法时可以使用this来指定调用哪一个构造方法
package mohe.com;

class Student
{
    int age;
    String Name;
    double Score;
    //假设有的学生不想让别人知道自己的体重,就设置为私有权限,外界没有办法访问
    private double weight = 100;

    Student()
    {
        System.out.println("无参构造方法被调用!!!");
    }

    Student(int age,String name)
    {
        //第五种情况的使用,调用构造函数
        this();
        //第三种情况
        this.age = age;
        this.Name = name;
        System.out.println("Student 的构造函数被调用!!!");
    }

    //方法,也就是函数
    void Print()
    {
        //第一种情况使用
        System.out.println(this.Name+" "+this.age);
        //第四种情况
        this.TestFunc();
    }

    void TestFunc()
    {
        Student tmp = this;//第二种
        System.out.println("You call the func");
    }
}

class pupil extends Student //子类
{
    int age;
    String Name;
    double Score;

    //相比于父类新增加的
    double Money;
    int grade;
    pupil(int age,String name,double money)
    {
        super(age,name);//可以调用父类的构造函数
        Money = money;
        System.out.println("pupil的构造函数被调用!!!");
    }
}

public class helloidea {
    public static void main(String[] args)
    {
        //new 一个对象
        Student stu1 = new Student(20,"Mohe");
        stu1.Print();
    }
}

结果展示:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值