Java "This" reference(引用)

When you instantiate an object from a class, memory is reserved for each instance field in the class. For example, if a class contains 20 data fields, when you create one object from that class, enough memory is reserved to hold 20 values for that object. Fortunately, it is not necessary to store a separate copy of each variable and method for each instantiation of a class. Usually, you want each instantiation of a class to have its own data fields. When you want each object to have a unique field value, you do not define the field as static. When you create a method for a class, any object can use the same method. Luckily, in Java just one copy of each method in a class is stored, and all instantiated objects can use that copy.

Every object in Java is uniquely identified by its this reference. The this reference is the “handle”(pointer) to the object that is used to invoke methods or explicitly reference instance variables.

The “this” reference is the mechanism that is used to tie them together at run-time. The this reference as a hidden first argument to every non-static class method. Static “class” methods do not have a this reference passed to them.

It is not possible to refer to the this variable in a static method of a class.

class Foo {

   int x;

   static int f() { return this.x; } // ERROR

}

Commonly static methods are used all the time in Java.

import java.net.*; // need to import InetAddress class

publicclass Host {

    static String host;

    static String user;

    staticfinalinterr = -1; // same as const int err = -1 in C++

    publicstaticvoid main (String[] args)

    {

        try {

            InetAddress addr = InetAddress.getLocalHost();

            host = addr.getHostName();

            user = System.getProperty("user.name");

            System.out.println(user + "@" + host); // string concatenation

        }catch (Exception e) {

            System.err.println(e); System.exit(err);

        }

    }

}

Output:

mz50947@APACCNSHZJN0764

The System.getProperty method is a static method defined as part of the java.lang.System class that returns a String containing the value of system property “user.name”.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值