您的位置:程序门 -> java -> j2se / 基础类



分数少了点希望大家能帮我理解一下this


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


分数少了点希望大家能帮我理解一下this[已结贴,结贴人:jxpxlq]
发表于:2007-01-30 11:03:28 楼主
public   class   flower   {
    private   int   petalcount   =   0;
    private   string   s   =   new   string( "null ");
    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(s);   //   can 't   call   two!
        this.s   =   s;   //   another   use   of   "this "
        system.out.println( "string   &   int   args ");
    }
    flower()   {
        this( "hi ",   47);
        system.out.println(
            "default   constructor   (no   args) ");
    }
    void   print()   {
//!         this(11);   //   not   inside   non-constructor!
        system.out.println(
            "petalcount   =   "   +   petalcount   +   "   s   =   "+   s);
    }
    public   static   void   main(string[]   args)   {
        flower   x   =   new   flower();
        x.print();
    }
}
我有几点不太明白.代码里的s在流程里的内容是 "hi "而一些构造函数里的this.s怎么就会是null了?希望高手能帮我分析一下this( "hi ",   47)和flower(string   s,   int   petals)会产生什么样的影响?还有就是private   string   s   =   new   string( "null ");又改变了什么?谢谢!
发表于:2007-01-30 11:15:321楼 得分:3
搞清楚变量的初始化和构造方法调用顺序
发表于:2007-01-30 12:01:242楼 得分:0
你好,,我顺序清楚了..就是不清楚this.s和s是指的同一个变量?
发表于:2007-01-30 17:08:333楼 得分:5
顺序清楚了这就没什么问题了吧,this.s是类中   的变量     或者说是类的属性     s是传个flower方法的一个参数     他们没任何关系     不过就是在这个构造方法中把属性s指向了传过来的s
发表于:2007-01-30 17:09:514楼 得分:0
private   string   s   =   new   string( "null ");又改变了什么?谢谢!

这个就是初始化   你看看string类就知道了   多看api有好处地:)
发表于:2007-01-30 18:55:155楼 得分:1
this   返回的是当前对象的引用。在这里也就是当前类的引用。同时他又能调用当前类的构造方法。由于他是实例对象,所以不能出现在静态(类)方法中!!
发表于:2007-01-31 10:00:146楼 得分:1
this类构造方法!!!


快速检索

最新资讯
热门点击