【问题标题】:Using the keyword "this" in java [duplicate]在java中使用关键字“this”[重复]
【发布时间】:2010-10-09 07:40:40
【问题描述】:

我试图了解 java 关键字 this 的实际作用。 我一直在阅读 Sun 的文档,但我对 this 的实际作用仍然很模糊。

【问题讨论】:

  • @JasonC 问题只能与本站其他问题重复。

标签: java keyword


【解决方案1】:

“this”的作用非常简单。它拥有当前的参考 对象。

  • 这个关键字持有当前类实例的引用
  • 此关键字不能在静态函数或静态块中使用
  • 该关键字可用于访问实例的影子变量
  • 该关键字可用于在函数调用中将当前对象作为参数传递
  • 此关键字可用于创建构造函数链

来源:http://javaandme.com/core-java/this-word

【讨论】:

    【解决方案2】:

    每个对象都可以使用关键字 this(有时称为 this 参考)。

    首先让我们看一下代码

    public class Employee  {
    
    private int empId;
    private String name;
    
    public int getEmpId() {
        return this.empId;
    }
    
    public String getName() {
        return this.name;
    }
    
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    

    }

    在上面的方法getName()中返回实例变量名。 现在让我们再看看类似的代码是

    public class Employee  {
    
    private int empId;
    private String name;
    
    public int getEmpId() {
        return this.empId;
    }
    
    public String getName() {
    
        String name="Yasir Shabbir";
        return name;
    }
    
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    
    public static void main(String []args){
        Employee e=new Employee();
        e.setName("Programmer of UOS");
    
        System.out.println(e.getName());
    
    }
    

    }

    输出 亚西尔·沙比尔

    • 此运算符始终与实例变量一起使用(属于对象) 不是任何类变量(属于类)
    • 这总是指类非静态属性而不是任何其他参数或局部变量。
    • 这总是在非静态方法中使用
    • 此运算符不能用于静态变量(类变量)

    **注意:**当方法包含参数或局部变量时,通常会出现逻辑错误 与类的字段同名。在这种情况下,如果您希望访问 类的字段——否则将引用方法参数或局部变量。

    【讨论】:

      【解决方案3】:

      “this”关键字是指当前对象,由于该对象正在执行该方法。当实例变量和局部变量具有相同名称时,它还用于避免在方法中作为参数传递的局部变量与实例变量之间的歧义。

      示例 ::

      public class ThisDemo1 
      {
          public static void main(String[] args) 
         {
              A a1=new A(4,5);       
         }
      }
      
      class A
      {
          int num1;
          int num2;
      
          A(int num1)
          {
              this.num1=num1; //here "this" refers to instance variable num1. 
             //"this" avoids ambigutiy between local variable "num1" & instance variable "num1"
      
              System.out.println("num1 :: "+(this.num1));
          }
      
          A(int num, int num2)
          {
              this(num); //here "this" calls 1 argument constructor within the same class.
              this.num2=num2;
              System.out.println("num2 :: "+(this.num2)); 
             //Above line prints value of the instance variable num2.
          }
      }
      

      【讨论】:

        【解决方案4】:

        The keyword this is a reference to the current object。最好用下面这段代码来解释:

        public class MyClass {
        
            public void testingThis() 
            {
                // You can access the stuff below by 
                // using this (although this is not mandatory)
        
                System.out.println(this.myInt);
                System.out.println(this.myStringMethod());
        
                // Will print out:
                // 100
                // Hello World
            }
        
            int myInt = 100;
            string myStringMethod() 
            {
                return "Hello World";
            }
        
        }
        

        除非您有代码标准告诉您使用this 关键字,否则它不会被大量使用。它有一个常见的用途,那就是如果您遵循代码约定,您的参数名称与您的类属性相同:

        public class ProperExample {
            private int numberOfExamples;
        
            public ProperExample(int numberOfExamples) 
            {
                this.numberOfExamples = numberOfExamples;
            }
        }
        

        this 关键字的一个正确用法是链接构造函数(使构造对象在整个构造函数中保持一致):

        public class Square {
            public Square() 
            {
                this(0, 0);
            }
        
            public Square(int x_and_y) 
            {
                this(x_and_y, x_and_y);
            }
        
            public Square(int x, int y)
            {
               // finally do something with x and y
            }
        }
        

        此关键字的工作方式相同,例如C#。

        【讨论】:

        • 这段代码不正确,静态方法没有引用这个。
        • 它可以编译吗?不应从静态方法访问对象元素
        • 不,它没有。 main() 是一个静态方法,因此没有“this”指针,因为没有对象在调用它。这不应该编译。
        • 哎呀。我匆忙写了一个例子。修复它。
        • 这是另一个糟糕的例子,说明如何使用“this”,以及为什么它对 OO 范式至关重要。
        【解决方案5】:

        它也可以是访问当前上下文信息的一种方式。 例如:

        public class OuterClass
        {
          public static void main(String[] args)
          {
            OuterClass oc = new OuterClass();
          }
        
          OuterClass()
          {
            InnerClass ic = new InnerClass(this);
          }
        
          class InnerClass
          {
            InnerClass(OuterClass oc)
            {
              System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
              System.out.println("This class: " + this + " / " + this.getClass());
              System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
              System.out.println("Other way to parent: " + OuterClass.this);
            }
          }
        }
        

        【讨论】:

          【解决方案6】:

          它是在同一个类的方法中一个类的实际实例的引用。 编码

          public class A{
              int attr=10;
          
              public int calc(){
               return this.getA()+10;
             }
             /**
             *get and set
             **/    
          
          }//end class A
          

          calc()体中,软件在当前分配的对象内部运行一个方法。

          对象的行为怎么可能看到自己?正是 this 关键字。

          真的,this 关键字不需要强制使用(如 super),因为 JVM 知道在内存区域中调用方法的位置,但在我看来,这使代码更具可读性。

          【讨论】:

            【解决方案7】:

            关键字this在不同的上下文中可能意味着不同的东西,这可能是你困惑的根源。

            它可以用作引用当前方法被调用的实例的对象引用:return this;

            它可以用作对象引用,引用当前构造函数正在创建的实例,例如访问隐藏字段:

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

            它可用于从构造函数中调用类的不同构造函数:

            MyClass()
            {
                this("default name");
            }
            

            它可用于从嵌套类中访问封闭实例:

            public class MyClass
            {
                String name;
            
                public class MyClass
                {
                    String name;
            
                    public String getOuterName()
                    {
                        return MyClass.this.name;
                    }
                }
            }
            

            【讨论】:

            • 1#“this”是否只能通过构造函数使用和编写? 2#this.setTittle("Tittle of Fram")呢;如您所见,它用于调用方法,但我不明白它的语义??
            • @user2019510:不,它不仅用于构造函数;我的答案包含不同用途的示例。是的,它用于调用方法,在这种情况下,它表示当前对象,并且就像使用任何其他对象引用来调用方法一样。
            • 感谢您的帮助@Michael:)
            【解决方案8】:

            用英文来想,“this object”就是你当前拥有的那个对象。

            WindowMaker foo = new WindowMaker(this);
            

            例如,您当前位于从 JFrame 扩展的类中,并且您希望传递对 JFrame 的 WindowMaker 对象的引用,以便它可以与 JFrame 交互。您可以通过将 JFrame 的引用传递给名为“this”的对象来传递对 JFrame 的引用。

            【讨论】:

              【解决方案9】:

              关键字'this'指的是当前对象的上下文。在许多情况下(正如Andrew 指出的那样),您将使用显式 this 来明确表示您指的是当前对象。

              另外,来自'this and super':

              *还有其他用途。有时,在编写实例方法时,需要将包含该方法的对象作为实际参数传递给子例程。在这种情况下,您可以将其用作实际参数。例如,如果您想打印出对象的字符串表示,您可以说“System.out.println(this);”。或者您可以在赋值语句中将 this 的值赋给另一个变量。

              事实上,你可以用它做任何你可以用任何其他变量做的事情,除了改变它的值。*

              该网站还提到了“super”的相关概念,这可能有助于理解这些如何与继承一起工作。

              【讨论】:

                【解决方案10】:

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

                class Foo
                {
                    private int bar;
                
                    public Foo(int bar)
                    {
                        // the "this" keyword allows you to specify that
                        // you mean "this type" and reference the members
                        // of this type - in this instance it is allowing
                        // you to disambiguate between the private member
                        // "bar" and the parameter "bar" passed into the
                        // constructor
                        this.bar = bar;
                    }
                }
                

                另一种思考方式是,this 关键字就像一个人称代词,您可以用来指代自己。其他语言对相同的概念有不同的词。 VB 使用Me,而Python 约定(因为Python 不使用关键字,只是每个方法的隐式参数)是使用self

                如果您要引用本质上属于您的对象,您会这样说:

                我的手臂或我的

                this 视为一种类型说“我的”的方式。所以一个伪代码表示应该是这样的:

                class Foo
                {
                    private int bar;
                
                    public Foo(int bar)
                    {
                        my.bar = bar;
                    }
                }
                

                【讨论】:

                • 您可以在没有“this”的情况下执行上述操作,例如使用匈牙利符号。 m_bar = 酒吧。所以并没有真正解释这对什么真正重要。
                • 能避免这样奇怪的结构吗?
                • @ng:不能重命名字段怎么办?就像它是来自超类的受保护字段一样?
                • @ng - 你说得对,我对“this”的使用很容易被谨慎的命名约定所取代。但是我相信我给出了最简单的例子,因为很明显 OP 只是在学习 OOP,并且可能难以理解“this”的更高级用法。
                • @Andrew 很好的解释。
                【解决方案11】:

                更好地利用这个

                public class Blah implements Foo {
                
                   public Foo getFoo() {
                      return this;
                   }
                }
                

                它允许您在当前上下文中专门“this”对象。另一个例子:

                public class Blah {
                
                   public void process(Foo foo) { 
                      foo.setBar(this);
                   }
                }
                

                你还能怎么做这些操作。

                【讨论】:

                • 对于您的第一个示例:从对象返回“this”确实没有意义。调用者已经引用了你的对象,否则他将如何调用该方法?
                • @eljenso:如果“返回这个;”是方法中唯一的一行,那么是的,它非常没用。但如果是例如一个setter,它允许你做方法链:myFoo.setBar(myBar).setBaz(myBaz).setMyInt(1);
                • 不仅如此,如果返回 this 是接口实现的特征怎么办?我挑战你向我展示一个在某些时候不需要返回的复杂项目。这是大多数 OO 系统的关键要求。
                • @mmyers 我同意,我忘了那个。
                • @ng 每个调用者都会在 Foo 的(子)类型上调用 getFoo()。如果你能做到 Blah blah = new Blah(); 为什么要使用该方法? foo foo = blah;也许我们可以扭转局面,你可以给我看一个项目,如你所描述的那样返回“this”,这样我就能更好地理解你想说什么。
                【解决方案12】:

                “this”是对当前对象的引用。

                查看详情here

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2011-01-26
                  • 2012-04-15
                  • 2011-10-10
                  • 2019-11-18
                  • 1970-01-01
                  • 2010-10-25
                  • 2020-05-01
                  相关资源
                  最近更新 更多