java中的this怎么用
这篇文章运用简单易懂的例子给大家介绍java中的this怎么用,代码非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

创新互联坚信:善待客户,将会成为终身客户。我们能坚持多年,是因为我们一直可值得信赖。我们从不忽悠初访客户,我们用心做好本职工作,不忘初心,方得始终。10多年网站建设经验创新互联是成都老牌网站营销服务商,为您提供成都做网站、成都网站制作、网站设计、H5网站设计、网站制作、品牌网站制作、微信平台小程序开发服务,给众多知名企业提供过好品质的建站服务。
什么是this?
this是自身的一个对象,代表对象本身,可以理解为:指向对象本身的一个指针。
用法如下:
用"this.成员变量名称"和重名的局部变量区分开来;
用"this.成员方法名"访问成员方法。
class Person{
private String name;//成员变量
private int age;
Person(){}
Person(String name){//局部变量
this.name=name;//1.用"this.成员变量名称"和重名的局部变量区分开来
}
Person(String name,int age){
this(name);
this.age=age;
}
String getInfo(){//成员方法
return "姓名:" + name + "\n年龄:" + age;
}
void print(){
System.out.println(this.getInfo());//2.用"this.成员方法名"访问成员方法。
System.out.println(getInfo());//这种情况this关键字一般不写,让编译器自动添加。
}
}
public class Test0505{
public static void main(String[] args){
Person p=new Person("张三",33);
p.print();
}
}this()访问构造方法必须放在构造方法的第一行
class Person{
private String name;
private int age;
Person(){}
Person(String name){//不含this()的构造方法
this.name=name;
}
Person(String name,int age){//在构造方法内调用另一个构造方法
this(name);//3."this();"访问构造方法必须放在构造方法的第一行
this.age=age;
}
String getInfo(){
return "姓名:" + name + "\n年龄:" + age;
}
void print(){
System.out.println(this.getInfo());
}
}
public class Test0505{
public static void main(String[] args){
Person p=new Person("张三",33);
p.print();
}
}返回对当前对象的引用
class Leaf{
private int i=0;
Leaf increment(){
i++;
return this;//4.返回对当前对象的引用。
}
void print(){
System.out.println("i="+i);
}
}
public class Test0505{
public static void main(String[] args){
Leaf x=new Leaf();
x.increment().increment().increment().print();
}
}将对当前对象的引用作为参数传递给其他方法
class Person{
void eat(Apple apple){
Apple peeled=apple.getPeeled();
System.out.println(peeled);
}
}
class Apple{
Apple getPeeled(){
System.out.println(this);//输出对当前对象的引用。
return Peeler.peel(this);//5.将对当前对象的引用作为参数传递给其他方法。
}
}
class Peeler{
static Apple peel(Apple apple){
return apple;
}
}
public class Test0505{
public static void main(String[] args){
Apple a=new Apple();
System.out.println(a);
new Person().eat(a);
}
}关于java中的this怎么用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
网站标题:java中的this怎么用
URL分享:http://www.jxjierui.cn/article/gcjegi.html


咨询
建站咨询
