zoukankan      html  css  js  c++  java
  • java关键字之this关键

    对象创建的过程和this的本质

    构造方法是创建Java对象的重要途径,通过new关键字调用构造器时,构造器也确实返回该类的对象,但这个对象并不是完全由构造器负责创建。创建一个对象分为如下四步:

    1)       分配对象空间,并将对象成员变量初始化为0或空

    2)       执行属性值的显示初始化

    3)       执行构造方法

    4)       返回对象的地址给相关的变量

    this的本质就是“创建好的对象的地址”!

    由于在构造方法调用前,对象已经创建。因此,在构造方法中也可以使用this代表“当前对象” 。

    this的三个应用场景

    1. 初始化对象属性
    2. 调用带参或无参构造器(必须位于构造器第一句)
    3. 调用当前对象的属性或方法(位置不限)

    注意事项

    this不能用于static方法中,main方法也是static方法。(因为方法区中没有对象)

    测试代码如下:

    public class TestThis {
        int a, b, c;
        // 无参构造器
        TestThis() {
            System.out.println("正要new一个Hello对象");
        }
        // 带参构造器1
        TestThis(int a, int b) {
            this(); // 作用1:调用无参的构造方法,并且必须位于第一行!
            a = a;// 这里都是指的局部变量而不是成员变量
            this.a = a;// 作用2:初始化对象属性 这样就区分了成员变量和局部变量. 
            this.b = b;
        }
        // 带参构造器2
        TestThis(int a, int b, int c) {
            
            this(a, b); //也是作用1:调用带参的构造方法,并且必须位于第一行!
            this.c = c;
        }
        // 普通方法1
        void sing() {
        }
        // 普通方法2
        void chifan() {
            System.out.println("你妈妈喊你回家吃饭!");
            System.out.println(this.a); //作用3:普通方法中调用当前对象的属性或方法 可以位于任意位置
            this.sing(); // sing();
        }
        public static void main(String[] args) {
            TestThis hi = new TestThis(2, 3);
            hi.chifan();
        }
    }

    this测试代码2:

    public class Student2 {
        // 静态的数据
        String name;
        int id;
    
        public void SetName(String name) {
            this.name = name;
        }
        // 说白了 加了this.之后指的就是这个类里面的东西,不是方法里面的。
    
        
        public Student2(String name, int a) {
            //this();        // 通过this调用其他无参构造方法。必须位于第一句!
            this(name);   //通过this调用其他有参数构造方法。必须位于第一句!
            this.name = name;
            this.id = a;
            System.out.println("通过this调用其他无参构造方法1");
    
        }
    
        public Student2() {  
            System.out.println("空构造方法构造一个对象");
        }
    
    
        public Student2(String name) {
            this.name = name;
            System.out.println("通过this调用其他有参数构造方法2");
        }
    
    }
    测试:
    public class testStudent2 {
        public static void main(String[] args) {
            //Student2  st = new Student2("任进",18);
            Student2  st2 = new Student2("任进",18);
        }
    }
    运行结果:
    通过this调用其他有参数构造方法2
    通过this调用其他无参构造方法1
    通过this调用其他有参数构造方法2
    通过this调用其他无参构造方法1
  • 相关阅读:
    Allegro PCB Design GXL (legacy) 使用slide无法将走线推挤到焊盘的原因
    OrCAD Capture CIS 16.6 导出BOM
    Altium Designer (17.0) 打印输出指定的层
    Allegro PCB Design GXL (legacy) 将指定的层导出为DXF
    Allegro PCB Design GXL (legacy) 设置十字大光标
    Allegro PCB Design GXL (legacy) 手动更改元器件引脚的网络
    magento产品导入时需要注意的事项
    magento url rewrite
    验证台湾同胞身份证信息
    IE8对css文件的限制
  • 原文地址:https://www.cnblogs.com/lanmao123/p/10489616.html
Copyright © 2011-2022 走看看