JAVA this用法
来源:互联网 发布:newifi 网络直通车 编辑:程序博客网 时间:2024/05/16 09:33
转帖this的用法方便自己以后查看
必须用this关键字的三种情况:
1、我们想通过构造方法将外部传入的参数赋值给类的成员变量,构造方法的形式参数名称与类的成员变量名相同。例如:
class Person
{
String name;
public Person(String name)
{
this.name = name;
}
}
{
String name;
public Person(String name)
{
this.name = name;
}
}
class Container
{
Component comp;
public void addComponent()
{
comp = new Component(this);
}
}
class Component
{
Container myContainer;
public Component(Container c)
{
myContainer = c;
}
}
{
Component comp;
public void addComponent()
{
comp = new Component(this);
}
}
class Component
{
Container myContainer;
public Component(Container c)
{
myContainer = c;
}
}
public class Person
{
String name;
int age;
public Person(String name)
{
this.name = name;
}
public Person(String name,int age)
{
this(name);
this.age = age;
}
}
{
String name;
int age;
public Person(String name)
{
this.name = name;
}
public Person(String name,int age)
{
this(name);
this.age = age;
}
}
1.this可指代对象自己本身: 当在一个类中要明确指出使用对象自己的属性或方法时就应该加上this引用,如下例 子:
输出的结果为: Maybe=love you
this.Maybe=love
this.Maybe=love you
第一行直接对构造函数中传递过来的参数Maybe进行输出,第二行是对成员变量(属性) Maybe的输出,第三行是先对成员变量(属性)Maybe赋值后进行输出。
2.在一个构造函数中调用另一个构造函数时,用this关键字:
以下例子:
public class Flower{
private int petalCount=0;
private String s=new String("null");
public Flower(int petals){
petalCount=petals;
}
public Flower(String ss){
s=ss;
}
public Flower(String s,int petals){
this(petals); //java中在一个构造函数中可以调用一次其他的构造函数,并且这条语句 必须在这个构造函数的第一行
this.s=s;
}
}
private int petalCount=0;
private String s=new String("null");
public Flower(int petals){
petalCount=petals;
}
public Flower(String ss){
s=ss;
}
public Flower(String s,int petals){
this(petals); //java中在一个构造函数中可以调用一次其他的构造函数,并且这条语句 必须在这个构造函数的第一行
this.s=s;
}
}
public class love{
String Maybe="love";
public love(String Maybe){
System.out.println("Maybe=" + Maybe);
System.out.println("this.Maybe="+this.Maybe);
this.Maybe=Maybe;
System.out.println("this.Maybe="+this.Maybe);
}
public static void main(String[] args){
love s=new love("love you");
}
}
String Maybe="love";
public love(String Maybe){
System.out.println("Maybe=" + Maybe);
System.out.println("this.Maybe="+this.Maybe);
this.Maybe=Maybe;
System.out.println("this.Maybe="+this.Maybe);
}
public static void main(String[] args){
love s=new love("love you");
}
}
- JAVA this用法
- java之this用法
- java中 this用法
- java中的this用法
- JAVA的this用法
- JAVA中this用法
- java this 用法
- [Java] this 用法总结
- java中this用法
- JAVA中this用法
- java 中this用法
- Java this 关键字用法
- java中this用法
- Java this 关键字用法
- java 中的this用法
- Java - this的用法
- java This的用法
- java----this的用法
- Windows程序设计摘录
- Oracle 快速删除重复记录
- 一个搜索文章合集的博客
- JavaScript Event
- JS 右键菜单功能
- JAVA this用法
- c
- 必须掌握的八个【cmd 命令行】
- 某人被蟒蛇吞了,请问在野外真的遇到蟒蛇怎么办
- ascill表
- SQL Server开发的二十一条军规
- mlabel的使用
- 感觉不那么对
- 关于细分行业软件未来趋势