Constructor构造方法

我们写一个car类,并写一个无参构造方法。

1 public class Car {
2     int speed;
3     //构造方法名字和 类一致 区分大小写 不需要写返回值 和参数列表
4     public Car(){
5         System.out.println("给我造一辆GTR!");
6     }
7 }

我们来创建一个对象car

 1 public class TestConstructor {
 2 
 3     /**
 4      * new关键字调用
 5      * 构造方法有返回值是个地址 不需要我们定义 也不需要return
 6      * 如果我们没有定义构造方法 系统会自动定义一个无参构造方法
 7      * 构造方法名 必须和 类名一致 区分大小写
 8      * 构造该类的对象 也经常用来初始化 对象的属性       见 Point 那个构造方法
 9      */
10     public static void main(String[] args) {
11         Car c = new Car();
12         
13     }
14 
15 }
构造该类的对象 也经常用来初始化 对象的属性 我们来看一下代码。
 1 public class Point {
 2     double x,y,z;
 3     
 4     public Point(double _x,double _y,double _z){
 5         x=_x;
 6         y=_y;
 7         z=_z;
 8         
 9     }
10     
11     public void setX(double _x){
12         x=_x;
13     }
14     public void setY(double _y){
15         y=_y;
16     }
17     public void setZ(double _z){
18         z=_z;
19     }
20     
21     //点到点的距离 方法
22     public double distance(Point p){
23         //Math.sqrt(); 是开方函数 
24         return Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y) +(z-p.z)*(z-p.z));
25     }
当然当我们学了this,上面的代码就写成下面的样子。因为this指向对象本身,这样就没有歧义。
 1 public class Point {
 2     double x,y,z;
 3     
 4     public Point(double x,double y,double z){
 5         this.x=x;
 6         this.y=y;
 7         this.z=z;
 8         
 9     }
10     
11     public void setX(double x){
12         this.x=x;
13     }
14     public void setY(double y){
15         this.y=y;
16     }
17     public void setZ(double z){
18         this.z=z;
19     }
20     
21     //点到点的距离 方法
22     public double distance(Point p){
23         //Math.sqrt(); 是开方函数 
24         return Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y) +(z-p.z)*(z-p.z));
25     }

写个main方法,看下效果。

 1     public static void main(String[]args){
 2         Point p = new Point(3,4,8);
 3         Point p2 = new Point(3,5,8);
 4         System.out.println(p.x);
 5         System.out.println(p.y);
 6         System.out.println(p.z);
 7         System.out.println(p2.x);
 8         System.out.println(p2.y);
 9         System.out.println(p2.z);
10         System.out.println(p.distance(p2));
11         
12 
13         p.setX(3);
14         p.setY(5);
15         p.setZ(8);
16         System.out.println(p.x);
17         System.out.println(p.y);
18         System.out.println(p.z);
19         
20         //p点到p2点的距离
21         System.out.println(p.distance(p2));
22     }
23 }

控制台打印

3.0
4.0
8.0
3.0
5.0
8.0
1.0



3.0
5.0
8.0
0.0

 构造器不能被继承 只能被调用 所以不存在overwrite 但可以overload

原文地址:https://www.cnblogs.com/PoeticalJustice/p/7608683.html