java this


package a.b;
/*
    this關鍵字調用其他的構造函數要注意的事項:
        1. this關鍵字調用其他的構造函數時,this關鍵字必須要位於構造函數中 的第一個語句。
        2. this關鍵字在構造函數中不能出現相互調用 的情況,因為是一個死循環。

    */
    class Student1{

        int id;  //身份證

        String name;  //名字

        //目前情況:存在同名 的成員 變量與局部變量,在方法內部默認是使用局部變量的。
        public Student1(int id,String name){  //一個函數的形式參數也是屬於局部變量。
            this(name); //調用了本類的一個參數的構造方法
            //this(); //調用了本類無參的 構造方法。
            this.id = id; // this.id = id 局部變量的id給成員變量的id賦值
            System.out.println("兩個參數的構造方法被調用了...");
        }
        
        
        public Student1(){
            System.out.println("無參的構造方法被調用了...");
        }

        public Student1(String name){
            this.name = name;
            System.out.println("一個參數的構造方法被調用了...");
        }

    }

    public class this1 {

        public static void main(String[] args) 
        {
            Student1 s = new Student1(110,"鐵蛋");
            System.out.println("編號:"+ s.id +" 名字:" + s.name);
    /*
        
            Student s2 = new Student("金胖子");
            System.out.println("名字:" + s2.name);
        */
        }
    }


//

一個參數的構造方法被調用了...
兩個參數的構造方法被調用了...
編號:110 名字:鐵蛋

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM