• 4.2Java对象创建过程和this的本质


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

    本章内容

    • 对象创建的过程

    • this关键字的本质


    对象创建的过程

    步骤:

    • 分配对象空间,并将对象成员变量初始化为0或空---方法区

    • 执行属性值的显式初始化

    • 执行构造方法---在这之前对象已经建好了

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

    this

    this的使用域

    • 用于普通的方法和构造器

    this的本质:

    • 创建好的对象的地址

    特点:

    • 在构造方法调用前,对象已经创建。

    • 在构造方法中也可以使用this代表"当前对象"---注意这里的类信息,所以用static修饰的是类信息不是对象,写了this会发现类里面没有对象。所以在static方法中不能用this也不能调用普通的方法。因为没有

    作用:

    • 代表当前方法所带的对象

    用法:

    • 通过this区分局部变量和成员变量

      • 实例:

      • /**
        * 测试this关键字
        * @author Lucifer
        */
        public class User {
           //定义三个属性
           int id;
           String name;
           String pwd;

           public User(){
          }
           public User(int id, String name){
               System.out.println("正在初始化已经创建好的对象:" + this);
               this.id = id; //不写this,无法区分局部变量id和成员变量id
               this.name = name;
          }

           public void login(){
               System.out.println(this.name + ",要登录!"); //不写this效果一样
          }

           public static void main(String[] args) {
               User u3 = new User(101,"Lucifer");
               System.out.println("打印Lucifer对象:" + u3);
               u3.login();
          }
        }
      •  

    It's a lonely road!!!
  • 相关阅读:
    37.leetcode11_container_with_most_water
    36.leetcode8_string_to_integer
    34.leetcode15&5_time_limit_exceeded
    35.leetcode15_3Sum
    33.leetcode6_zigzag_conversion
    32.leetcode3_longest_substring_without_repeating_characters
    31.leetcode2_add_two_numbers
    29.leetcode172_factorial_trailing_zeroes
    30.leetcode171_excel_sheet_column_number
    [LeetCode] 43.Multiply Strings 字符串相乘
  • 原文地址:https://www.cnblogs.com/JunkingBoy/p/14613102.html
Copyright © 2020-2023  润新知