zoukankan      html  css  js  c++  java
  • 面向对象要点(this关键字)

    package day07;
    
    public class ThisKeywords {
        private String name;
        private void Foo(String name) {
            this.name = name;//将类中的属性赋值,通过this关键字,将函数参数中的name赋值给类中的name属性
            System.out.println("this.name is:"+this.name);
        }
        public static void main(String[] args) {
            ThisKeywords tk = new ThisKeywords();
            tk.name = "world";
            System.out.println(tk.name);
            tk.Foo("hello");
            System.out.println(tk.name);
            
            
        }
    
        
    
    }

    world
    this.name is:hello
    hello

     
    package day07;
    
    public class ThisKeywords {
        private int number;
        private  String name;
        ThisKeywords(int number)
        {
            this.number =number;
            System.out.println("this.number="+number);
            
        }
         ThisKeywords(String name) {
            // TODO Auto-generated constructor stub
            this.name = name;
            System.out.println("this.name="+name);
        
        }
         ThisKeywords(int number,String name)
         {
             this(number);
    //         this(name);虽然可以在一个构造函数中调用另外一个构造函数,但是不能使用相同的方法调用两个构造函数,而且被调用的构造函数放在最开始的位置
             this.name = name;
            
         }
         ThisKeywords() {
            // TODO Auto-generated constructor stub
             this(100,"Mark");
         }
        public static void main(String[] args) {
            
            ThisKeywords tk = new ThisKeywords();
        
            
        }

    }

    this.number=100

     

        在为类设计构造函数的时候,有时候会涉及多个构造函数来满足不同条件下的初始化,在一个构造函数中也往往需要调用另外一个构造函数来减少重复的代码,这是this关键字发挥的重要的作用。

     this关键字主要有三个应用:
     (1)this调用本类中的属性,也就是类中的成员变量;
     (2)this调用本类中的其他方法;
     (3)this调用本类中的其他构造方法,调用时要放在构造方法的首行。

        this表现形式一:当局部变量和成员变量同名的时候,可以用this关键字

        this表现形式二:构造函数之间的调用可以使用this关键字,后面跟上小括号,制定具体实参即可明确要调用的构造函数。*特殊情况:注意,调用本类中的构造函数的this语句必须定义在构造函数的第一行。

          

  • 相关阅读:
    Oracle关于快速缓存区应用原理
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.fileupload.RequestContext
    速记const 指针与指向const的指针
    bzoj3992【SDOI2015】序列统计
    ubuntu 1204 安装mysql
    解决getOutputStream() has already been called for this response
    把一个project相关的jar放到project的lib文件夹中
    解决eclipse偶尔无视breakpoint的行为
    解决eclipse无法打开:Failed to load the JNI shared library
    挣值管理公式集合
  • 原文地址:https://www.cnblogs.com/mmlovejj/p/5044525.html
Copyright © 2011-2022 走看看