Java this指针的使用 您所在的位置:网站首页 华中科技大学软件工程保研率 Java this指针的使用

Java this指针的使用

2023-11-19 19:55| 来源: 网络整理| 查看: 265

Java中关键字this指针只能用于方法内,当一个对象被创建后,JVM就会给这个对象分配一个引用自身的指针,这个指针就是this。this只能在类中的非静态方法中使用,静态方法和静态代码块中不能出现this。this只和特定对象关联,不个类关联,所以同一个类的不同对象有不同的this。 使用范围:

在方法内使用成员变量的时将当前对象传递给其他方法时在构造器中调用构造器时

示例

在方法中使用成员变量 public class person{ private String name; private int age; private String email; person(String name,int age,String email){ setName(name); setAge(age); setEmail(email); printInfo(); } public void setName(String name){ this.name=name; } public void setAge(int age){ this.age=age; } public void setEmail(String email){ this.email=email; } public void printInfo(){ System.out.println("name:"+name+",age:"+age+",email:"+email); } public static void main(String [] args){ person p=new person("xiaoming",12,"[email protected]"); } }

运行结果:name:xiaoming,age:12,email:[email protected]

将当前对象传递给其他方法 class Person{ public void eat(Apple apple){ Apple peeled =apple.getPeeled(); System.out.println("Yummy"); } } class Peeler{ static Apple peel(Apple apple){ // ...remove peel return apple;//peeled } } class Apple{ Apple getPeeled(){ return Peeler.peel(this); } } public class PassingThis{ public static void main(String [] args){ new Person().eat(new Apple()); } }

运行结果:Yummy

在构造器中调用构造器 public class Flower{ int petalCount=0; String s ="initial value"; Flower(int petals){ petalCount=petals; System.out.println("Constructor w/int arg only,petalCount ="+petalCount); } Flower(String ss){ System.out.println("Constructor w/ String arg only,s ="+ss); s=ss; } Flower(String s,int petals){ this(petals);//可以用this调用一个构造器,但却不能调用两个,必须将构造器调用置于最起始处,否则会编译出错。 //!can't call two this.s=s;//Another use of this petalCount=petals; System.out.println("Strng & int args"); } Flower(){ this("hi",47); System.out.println("default constructor (no args)"); } void printPetalCount(){ //!this (11),//not inside non-constructor System.out.println("petalCount ="+petalCount+ "s="+s); } public static void main(String [] args){ Flower x=new Flower(); x.printPetalCount(); } }

运行结果:

Constructor w/ String arg only,s =47 Strng & int args default constructor (no args) petalCount =47s=hi



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有