JAVA面向对象-----this的概述

this关键字代表是对象的引用。也就是this在指向一个对象,所指向的对象就是调用该函数的对象引用。

1:没有this会出现什么问题

1:定义Person类

1:有姓名年龄成员变量,有说话的方法。
2:定义构造方法,无参的,多个有参的。都要实现。

class Person {

    String name;
    int age;
    //无参数构造函数
    Person() {
        System.out.println("这是无参的构造函数");
    }

    //有参数构造函数
    Person(int a) {
        age = a;
        System.out.println("有参构造1");
    }
    //有参数构造函数
    Person(String n) {
        name = n;
        System.out.println("有参构造2");
    }
    //有参数构造函数
    Person(int a, String n) {
        age = a;
        name = n;
        System.out.println("有参构造");
    }

    //普通函数
    void speak() {
        System.out.println("hah");
    }
}

2;假设定义40个成员变量,第一个有参构造初始化20个变量,第二个有参构造需要初始化40个变量。

1:第二个有参构造想要使用第一个有参构造。
2:成员函数相互之间可以调用。构造函数可以吗?
3:编译失败,那么构造函数之间应该存在相互调用的模式。this就可以完成这个工作。

class Person {
    String name;
    int age;

    Person() {

    }
    Person(String n){
        name=n;
    }
    Person(String n, int a) {
        //编译报错
        Person(n);
        age = a;
    }
}

3:总结:实际工作中,存在着构造函数之间的相互调用,但是构造函数不是普通的成员函数,不能通过函数名自己接调用


2:this是什么

1:在构造函数中打印this
2:创建对象,打印对象名p
3:this和p是一样的都是内存地址值。
4:this代表所在函数所属对象的引用。

class Student {
    String name;
    String gender;
    int age;

    Student() {

    }

    Student(String name) {
        this();
        this.name = name;
    }

    Student(String name, String gender, int age) {
        this(name);
        System.out.println(this); // Student@c17164

        this.gender = gender;
        this.age = age;
    }

    void speak() {
        run();
        System.out.println("姓名:" + name + " 性别:" + gender + " 年龄:" + age
                + " 哈哈!!!");
    }

    void run() {
        System.out.println("run.....");
    }

}
class Demo2 {

    public static void main(String[] args) {

        Student p = new Student("jack", "男", 20);
        System.out.println(p); // Student@c17164

        Student p2 = new Student("rose", "女", 18);
        System.out.println(p2);

        p.speak();

    }
}

3:递归构造函数调用

1:构造函数的相互调用
在编译时期会报错

class Student {
    String name;
    String gender;
    int age;
    //构造函数见相互调用
    Student() {
        this(null);
    }
    //构造函数见相互调用
    Student(String name) {
        this();
        this.name = name;
    }

    Student(String name, String gender, int age) {
        this(name);
        this.gender = gender;
        this.age = age;
    }

    void speak() {
        run();
        System.out.println("姓名:" + name + " 性别:" + gender + " 年龄:" + age
                + " 哈哈!!!");
    }

    void run() {
        System.out.println("run.....");
    }

}

4:this只能在非静态中(没有static修饰的)函数使用

5:构造函数间相互调用必须放在构造函数的第一个语句中,否则编译错误

6:可以解决构造函数中对象属性和函数形参的同名问题。


【正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!下面有个“顶”字,你就顺手把它点了吧(要先登录CSDN账号哦 )】


—–乐于分享,共同进步!
—–更多文章请看:http://blog.csdn.net/duruiqi_fx


原文地址:https://www.cnblogs.com/hainange/p/6153869.html