首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >面试题12(如何正确使用this)

面试题12(如何正确使用this)

作者头像
Java学习
发布2018-04-13 14:33:59
8570
发布2018-04-13 14:33:59
举报
文章被收录于专栏:java学习java学习

哪些语句能放在如下代码中所示位置,而不会导致编译错误? public class ThisUse{ int plane; static int car ; public void dosomething(){ int i;

//插入语句

请选出3个正确的答案: ( a ) i=this.plane; ( b )i=this.car; ( c ) this=new ThisUse(); ( d ) this.car=plane;

考点:该面试题主要考察求职者对Java语言中this关键词的掌握和使用 出现频率:★★★ 【面试题解析】Java语言中,this用法可以分为下面3种。 1.this指代当前对象 当在一个类中要明确指出使用该类对象的变量或函数时,就应该加上this引用 public class A{ String s = " hello " public a ( string s ){ System . out . printin ( "s = " + s ) ; System . out . printin ( "1- > this . s= " + this.s );

this.s = s; System . out . println ( "2- > this . s = " + this . s ) ;

} public static void main ( string [ ] args ) { new A( " helloworld ! " ) ;

}

运行结果: s = helloworld ! 1- > this . s= hello 2- > this . s= helloworld ! 构造函数A中,参数s与类A的变量s同名,这时假如直接对s进行操作,则会对变量s进行修改。若要对类A的变量s进行操作,就应该使用this进行引用。运行结果的第1行就是直接对参数s进行打印结果,后面两行分别是对对象A的变量s进行操作前后的打印结果。 2.把this作为参数传递 当一个类要把自己作为参数传递给别的对象时,也可以用this。示例代码如下 public class A{ public A(){ new B(this).print();

}

public void print (){ System . out . println ( " hello from a !" ) ;

}

} public class B{ A a; public B (A a ) { this.a = a;

} public void print (){ a.print ( ) ; System ,.out . println ( " hello from b ! " ) }

}

运行结果: Hello from a ! Hello from b !

在这个例子中,对象A的构造函数中,用new B(this)把对象A自己作为参数传递给了对象B的构造函数。 3.注意匿名类和内部类中的this 有时候,会用到一些匿名类和内部类。当在匿名类或内部类中用this时,这个this则指的的是匿名类或内部类本身。这时假如要使用外部类的方法和变量的话,则应该加上外部类的类名。示例代码如下: public class A { int i=1; public A (){ Thread thread = new Thread ( ){ public void run ( ) { for ( ; ;) ( A . this.run ( ) ; try { sleep(1000); }catch ( Interruptedexception ie ){

}}}};

thread . start ();

} public void run ( ) { System , out . println ( ' i = " + i) ; 1++;

} public static void main ( string [ ] args ) throws exception ( new A();

}

} 在上面这个例子中, thread是一个匿名类对象,它的run()函数里用到了外部类的run()函数。这时由于函数同名,直接调用就不行了。这时有两种方法,第1种方法就是把外部的run函数换一个名字,但这种办法对于一个开发到中途的项目来说是不可取的。第2种方法就可以参考本例用外部类的类名加上this引用,来说明要调用的是外部类的方法run()方法。 注意:this引用不能用于静态上下文中,因为在任何对象的上下文中都不会执行静态代码。

面试题12中,非静态方法有一个隐含的this对象引用,但是该引用是不能被改变的所以(c)是错误的;(d)也是错误的,因为this是表示对象引用,不能指向局部变量。

参考答案:(a)、(b)、(e)。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-10-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 java学习 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档