构造方法的简单介绍

本文详细介绍了Java中的构造方法,包括其作用、创建对象的步骤、构造器的特点、重载示例以及如何使用`this`关键字进行对象初始化和避免重复代码。还通过课后作业展示了如何定义和使用Point类以及构造方法的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

构造方法(构造器 constructor)

构造器勇于对象的初始化,而不是创建对象

创建对象的四步

  1. 分配对象空间,并将对象成员变量初始化为0或空
  2. 执行属性值的显示初始化
  3. 执行构造方法
  4. 返回对象的地址给相关的变量

声明格式:

[修饰符] 类名 (形参){

​ //语句;

}

构造器的4个特点

  1. 构造器通过new关键字调用!!
  2. 构造器是没有返回值的,同时也不能定义返回值类型(返回值的类型是本类的类型),不能在构造器里使用return返回某个值
  3. 构造器的方法名必须和类名一致
  4. 如果没有定义构造器,那么编译器就会自动定义一个无参的构造方法。

课后作业

/**
 * 定义一个“点”(Point)类用来表示二维空间中的点(有两个坐标)。要求如下:
 * 可以生成具有特定坐标的点对象。
 * 提供可以计算该“点”距另外一点距离的方法。
 */


package com.zxp;

public class Point {
    double x,y;

    public Point(double _x, double _y) {
        this.x = _x;
        this.y = _y;
    }

    public double getDistence(Point p){
        double d = Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
        return d;
    }

    public static void main(String[] args) {
        Point p1 = new Point(3.0,4.0);
        Point o = new Point(0.0,0.0);
        System.out.println(p1.getDistence(o));
    }
}

构造方法的重载

构造方法也是方法。与普通方法一样,也可以重载

例如:利用构造方法创建不同的用户对象

/**
 * 测试构造方法的重载
 */


package com.zxp;

public class TestUser {
    int id;
    String name;
    int age;
    char sex;

    public TestUser(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public TestUser(int id, String name, char sex){
        this.id = id;
        this.name = name;
    }

    public TestUser(int id, String name, int age, char sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }


    public static void main(String[] args) {
        TestUser s1 = new TestUser(1001,"zxp");
        TestUser s2 = new TestUser(1003,"zxp",'男');
        TestUser s3 = new TestUser(1002,"zxp",18,'男');
    }

}

注意事项:

  • 如果方法构造中形参与属性名相同,需要使用this关键字区分属性与形参。this.id表示属性id,id表示形参id。

this关键字

在这里插入图片描述

this的用法

  • 在普通方法中,this总是指向调用该方法的对象

  • 在构造方法中,this总是指向正要初始化的对象

    this的其他要点

  • this()调用重载的构造方法,避免相同的初始化代码,但只能在构造方法中用,并且必须位于构造方法的第一句
  • this不能用于static方法中
  • this是作为普通方法的"隐式参数",有系统传入到方法中
/**
 * 测试this的使用
 */
package com.zxp;

public class TestThis {
    int a;
    int b;
    int c;

    public TestThis() {
        System.out.println("你妈妈喊你回家吃饭");
    }

    public TestThis(int a,int b){
        //TestThis();//不能这样调用构造方法,
        this();//这样可以调用无参构造,并且this()必须放在第一位
        //a = a,不可以这样使用前面的a是构造方法里面的成员变量,而不是局部变量
        this.a = a;
        this.b = b;
    }

    public TestThis(int a, int b, int c) {
        this(a,b);
        this.c = c;
    }

    public void kickball(){
        System.out.println("我在踢球,为我加油!");
    }

    public static void main(String[] args) {
        TestThis t1 = new TestThis(2,3);
        t1.kickball();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值