JAVA this用法

来源:互联网 发布:newifi 网络直通车 编辑:程序博客网 时间:2024/05/16 09:33
转帖this的用法方便自己以后查看
必须用this关键字的三种情况:
   1、我们想通过构造方法将外部传入的参数赋值给类的成员变量,构造方法的形式参数名称与类的成员变量名相同。例如:
        class Person
        
{
             String name;
             
public Person(String name)
             
{
                  
this.name = name;
             }
 
        }
2、假设有一个容器类和一个部件类,在容器类的某个方法中要创建部件类的实例对象,而部件类的构造方法要接受一个代表其所在容器的参数。例如: 
 class Container
        
{
             Component comp;
             
public void addComponent()
             
{
                  comp 
= new Component(this);
             }

        }

        
class Component
        
{
             Container myContainer;
             
public Component(Container c)
             
{
                  myContainer 
= c;
             }

        }

3、构造方法是在产生对象时被java系统自动调用的,我们不能再程序中像调用其他方法一样去调用构造方法。但我们可以在一个构造方法里调用其他重载的构造方法,不是用构造方法名,而是用this(参数列表)的形式,根据其中的参数列表,选择相应的构造方法。例如
 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;
             }

        }

 

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; 

                }
 

    }

 

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"); 

    }
 

 }
 

####################################################################################
原创粉丝点击