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

posted @ 2016-09-27 19:27  feia1236  阅读(3708)  评论(0编辑  收藏  举报