Java基礎之構造方法及其應用


  • 構造方法是一種特殊的方法,它是一個與類同名且無返回值類型(連void也不能有)的方法。
  • 對象的創建就是通過構造方法來完成,其功能主要是完成對象的初始化
  • 當類實例化一個對象時會自動調用構造方法。構造方法和其他方法一樣也可以重載。
  • 構造方法分為兩種:無參構造方法 有參構造方法
  • 類中必定有構造方法,若不寫,系統自動添加無參構造。(接口不能被實例化,所以接口中沒有構造方法。)

實例演示:計算坐標點的距離

實體類Point代碼:

 1 public class Point {
 2 
 3     // 點的屬性 橫縱坐標
 4     int x;
 5     int y;
 6     
 7     // 默認無參構造器 
 8     public Point(){
 9         System.out.println("默認構造。");
10     }
11     
12     // 有參構造1
13     public Point(int a,int b){
14         System.out.println("有參構造。");
15         // 給對象賦值 
16         x = a;
17         y = b;
18     }
19     // 有參構造2(重載)
20     public Point(int a){
21 //        System.out.println();
22         this(a,a); // 重載 調用上面的有參構造1(此語法專門用來構造方法間調用,必須寫在構造方法的第一行)
23     }
24     
25     /**
26      * 點距離的計算方法
27      * 參數分別為:無參 點坐標 點對象
28      * 方法重載
29      */
30     public double distance(){ // 無參
31         return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); // 到原點的距離
32     }
33     
34     // 到某個點的距離
35     public double distance(int a, int b){ // 參數為點坐標
36         return Math.sqrt(Math.pow(this.x-a, 2)+Math.pow(this.y-b, 2));
37     }
38     
39     public double distance(Point p){ // 參數為點對象
40         return distance(p.x, p.y);
41     }
42     
43 }

Demo:

 1 public class PointDemo {
 2     public static void main(String[] args) {
 3         
 4         Point p1 = new Point(3,2);
 5         System.out.println("p1的坐標是:" + "(" + p1.x + "," + p1.y + ")");
 6         
 7         Point p2 = new Point(5);
 8         System.out.println("p2的坐標是:" + "(" + p2.x + "," + p2.y + ")");
 9         
10         /**
11          * 求點到點的距離
12          */
13         Point p = new Point(6,8);
14         System.out.println("到原點的距離為:" + p.distance()); // 到原點的距離
15         System.out.println("到另一個點的距離為:" + p.distance(3, 3)); // 到(3,3)的距離 
16         System.out.println("到某個點對象的距離為:" + p.distance(p2)); // 到點對象p2的距離
17     }
18 }

 輸出為:

    有參構造。
    p1的坐標是:(3,2)
    有參構造。
    p2的坐標是:(5,5)
    有參構造。
    到原點的距離為:10.0
    到另一個點的距離為:5.830951894845301
    到某個點對象的距離為:3.1622776601683795


免責聲明!

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



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