內蒙古java團隊

          j2se,j2ee開發組
          posts - 139, comments - 212, trackbacks - 0, articles - 65
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          super和this

          Posted on 2010-08-09 10:22 帥子 閱讀(230) 評論(0)  編輯  收藏 所屬分類: j2se技術專區j2ee技術專區
          package test;

            public class ThisTest {

            private int i=0;

            //第一個構造器:有一個int型形參

            ThisTest(int i){

            this.i=i+1;//此時this表示引用成員變量i,而非函數參數i

            System.out.println("Int constructor i——this.i:? "+i+"——"+this.i);

            System.out.println("i-1:"+(i-1)+"this.i+1:"+(this.i+1));

            //從兩個輸出結果充分證明了i和this.i是不一樣的!

            }

            //? 第二個構造器:有一個String型形參

            ThisTest(String s){

            System.out.println("String constructor:? "+s);

            }

            //? 第三個構造器:有一個int型形參和一個String型形參

            ThisTest(int i,String s){

            this(s);//this調用第二個構造器

            //this(i);

            /*此處不能用,因為其他任何方法都不能調用構造器,只有構造方法能調用他。

            但是必須注意:就算是構造方法調用構造器,也必須為于其第一行,構造方法也只能調

            用一個且僅一次構造器!*/

            this.i=i++;//this以引用該類的成員變量

            System.out.println("Int constructor:? "+i+" "+"String constructor:? "+s);

            }

            public ThisTest increment(){

            this.i++;

            return this;//返回的是當前的對象,該對象屬于(ThisTest)

            }

            public static void main(String[] args){

            ThisTest tt0=new ThisTest(10);

            ThisTest tt1=new ThisTest("ok");

            ThisTest tt2=new ThisTest(20,"ok again!");

            System.out.println(tt0.increment().increment().increment().i);

            //tt0.increment()返回一個在tt0基礎上i++的ThisTest對象,

            //接著又返回在上面返回的對象基礎上i++的ThisTest對象!

            }

            }

            運行結果:

            Int constructor i——this.i:? 10——11

            String constructor:? ok

            String constructor:? ok again!

            Int constructor:? 21

            String constructor:? ok again!

            14

            注意:this不能用在static方法中!所以甚至有人給static方法的定義就是:沒有this的方法!雖然夸張,但是卻充分說明this不能在static方法中使用!

            //1.super運用在構造函數中

            class test1 extend test{

            public test1()...{

            super();//調用父類的構造函數

            }

            public test1(int x){

            super(x);//調用父類的構造函數,因為帶形參所以super 也要帶行參

            }

            }

            //2.調用父類中的成員

            class test1 extend test{

            public test1(){}

            public f(){//假如父類里有一個成員叫g();

            super.g();//super引用當前對象的直接父類中的成員

            }

            }

          主站蜘蛛池模板: 龙岩市| 灵宝市| 中卫市| 大连市| 康保县| 湄潭县| 巴林右旗| 义马市| 固镇县| 陕西省| 新乡市| 岑溪市| 章丘市| 湟中县| 临洮县| 卫辉市| 通化县| 大厂| 石门县| 泰州市| 赤城县| 新蔡县| 房产| 晋江市| 安宁市| 永和县| 平原县| 镇远县| 山阳县| 石台县| 札达县| 交城县| 乌拉特中旗| 东明县| 米易县| 梧州市| 敦化市| 日土县| 南澳县| 甘孜县| 临桂县|