刘志雄
[摘 要]java中的构造函数与this在程序当中起着非常重要的作用:构造函数主要用来完成对对象属性的初始化工作;this的作用类似于C语言里的指针。本文将结合简单实例对构造函数与this的一般用法与特殊用法进行详细分析。
[关键词]构造函数;java;对象;this
在一个类中,如果定义了与成员变量同名的形式参数,要区分到底是成员变量还是形式参数,通过this来进行区分。在Java的学习当中,this关键字起着指针的作用,用来指示成员变量与成员方法还有构造函数。在已有的文献当中分析构造函数与this的用法时,用例和分析过于复杂,下面用简单实例来全面分析构造函数与this的用法。
一、构造函数与this用法实例
用例如下:
class student{
1.int age;
2.String name;
3.student(){
// 5.1 student(age);
4.System.out.println("空構造函数");}
5.student(int age){
6.this();
7.this.age=age;
8.System.out.println("带一个形参的构造函数"); }
9.student(int age, String name){
10. this(age);
11. this.age=age;
12. this.name=name;
13. this.f();
14. System.out.println("带两个形参的构造函数"); }
15. void f(){
16. //this();
17. System.out.println("成员方法"); }
18.public static void main(String[] args){
19. student a1=new student();
20. student a2=new student(20,"小军");
21. System.out.println("年龄"+a2.age+"名字"+a2.name);}}
程序运行结果如下:
二、构造函数与this一般用法的分析
第3行.5行.9 行是定义student类的构造函数,第6行.10行是用this来调用构造函数;另外,构造函数不能相互调用:如第5.1行与第6行。第7行.11行.12行是this用来指示成员变量,使用this.age, this.name来指示成员变量。第13行表示在构造函数中调用了成员方法f()。第19行与第20行是创建了两个对象,实际是运行了空构造函数与带两个形参的构造函数。如果程序中保留第19行与第20行时,必须把空构造函数写出来。程序的第21行是对对象a2的属性值的输出。
三、this 的特殊用法
接下来分析this在匿名类和内部类中的应用。
用例如下:
1.public class animal {
2.animal(){
3.Thread thread = new Thread(){
4.public void run() {
5.animal.this.run(); } }; //注意这里有分号
6.thread.start(); }
7.public void run() {
9.System.out.println("我是成员方法run ");}
10. public static void main(String[] args) {
11. animal as=new animal();}}
程序运行结果:……p>