Java构造方法的使用

Java构造方法的使用方式

  1. 在主方法创建一个类的对象时,会直接调用该类的构造方法,如果没有书写该类的构造方法,那么系统会默认给其一个无参的构造方法,即类在使用时,必会调用其构造方法。

  2. 如果给类书写了一个有参的构造方法,在主方法创建该类的对象时没有传递相应参数,则会出现错误;即在类中创建了一个构造方法,系统不再为该类创建默认的无参构造方法。

代码示例:

class test
{
    test(int a,int b)
    {
        System.out.println("调用了有参的构造方法");
    }
}

public class conMethod03 {
    public static void main(String[] args) {
        test t1=new test(2,3);
    }
}

结果:

调用了有参的构造方法

Process finished with exit code 0

注: 如果不加入实参2和3,则无法运行。

  1. 如果该类继承了一个父类,则在主方法创建该类的对象时,首先会调用该类父类的构造方法,然后再调用该类的构造方法。

代码示例:

class comMethod03
{
    comMethod03()
    {
        System.out.println("调用父类的无参构造方法");
    }
    comMethod03(int a)
    {
        System.out.println("调用父类的有参构造方法。");
    }
}
class comMethod04 extends comMethod03
{
    comMethod04()
    {
        System.out.println("调用子类的无参构造方法.");
    }
    comMethod04(int a)
    {
        System.out.println("调用子类的有参构造方法。");
    }
}

public class comMethod02 {
    public static void main(String[] args) {
        comMethod04 c1=new comMethod04(5);
    }
}

结果:

调用父类的无参构造方法
调用子类的有参构造方法。

Process finished with exit code 0

注: 如果想要调用父类的有参构造方法,需要使用super() 方法。

  1. 构造方法的重载与一般方法的重载方式是一样的。可见方法的重载使用方式。https://blog.csdn.net/weixin_51355516/article/details/110202493.

  2. 在构造方法中调用重载的构造方法。

代码示例:

class Cylinder01
{
    private double radius;
    private int height;
    private static double pi=3.14;
    Cylinder01()
    {
        this(2.4,5);
        System.out.println("调用了无参的构造方法!!");
    }
    Cylinder01(double r,int h)
    {
        radius=r;
        height=h;
        System.out.println("调用了有参的构造方法!!!");
    }
}

public class comMethod11 {
    public static void main(String[] args) {
        Cylinder01 c1=new Cylinder01();
    }
}

结果:

调用了有参的构造方法!!!
调用了无参的构造方法!!

Process finished with exit code 0

注: 该形式的使用主要要清楚this的含义,其代表该类的对象。以后会专门做一篇关于this方法的使用。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值