有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (6) 个答案

  1. # 1 楼答案

    完全一样。因为你经常输入this.xyz,如果有一个字段的名字,而没有一个局部变量来隐藏它,这是一个快捷方式,意味着同样的事情

  2. # 2 楼答案

    使用this关键字可以消除成员变量和局部变量之间的歧义,例如函数参数:

    public MyClass(int integerField) {
        this.integerField = integerField;
    }
    

    上面的代码段将局部变量integerField的值分配给同名类的成员变量

    一些商店采用编码标准,要求所有成员访问都必须通过this认证。这是有效的,但不必要;在不存在冲突的情况下,删除this不会改变程序的语义

  3. # 3 楼答案

    Java tutorials开始:

    Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

    因此,当在对象中调用方法时,调用如下所示:

    public class MyClass{
    
        private int field;
    
        public MyClass(){
            this(10); // Will call the constructor with a int argument
        }
    
        public MyClass(int value){
        }
    
        //And within a object, the methods look like this
        public void myMethod(MyClass this){ //A reference of a object of MyClass
            this.field = 10; // The current object field
        }
    
    }
    
  4. # 4 楼答案

    this关键字指的是当前的object。 通常我们用this.memberVariable来区分成员变量和局部变量

    private int x=10;
    
         public void m1(int x) {
          sysout(this.x)//would print 10 member variable
          sysout(x); //would print 5; local variable
          } 
    
       public static void main(String..args) {
          new classInst().m1(5);
    
       }
    

    离开具体问题, 在Overloaded constructors中使用this

    我们可以使用它调用重载构造函数,如下所示:

    public class ABC {
         public ABC() {
          this("example");to call overloadedconstructor
          sysout("no args cons");
         }
          public ABC(String x){
             sysout("one argscons")
            }
    
     }
    
  5. # 5 楼答案

    在实例方法中,可能需要指定变量引用的范围。例如:

    private int x;
    
    public void method(int x) {
        System.out.println("Method x   : " + x);
        System.out.println("Instance x : " + this.x);
    }
    

    而在本例中,有两个x变量,一个是局部方法变量,一个是类变量。您可以用this来区分这两个选项

    有些人总是在使用类变量之前使用this。虽然这不是必需的,但它可能会提高代码的可读性

    至于多态性,您可以将父类称为super。例如:

    class A {
        public int getValue() { return 1; }
    }
    class B extends A {
        // override A.getValue()
        public int getValue() { return 2; }
    
        // return 1 from A.getValue()
        // have we not used super, the method would have returned the same as this.getValue()
        public int getParentValue() { return super.getValue(); }   
    }
    

    关键字thissuper都取决于使用它的范围;这取决于运行时使用的实例(对象)

  6. # 6 楼答案

    虽然它们的外观和行为相同,但在字段和方法参数之间共享相同的名称时会有差异,例如:

    private String name;
    
    public void setName(String name){
    
        this.name = name;
    
    }
    

    name是传递的参数,this.name是正确的类字段。 请注意,键入this.。。。提示您许多IDE中所有类字段[和方法]的列表