相关疑难解决方法(0)

Java默认构造函数

究竟什么是默认构造函数 - 你能告诉我以下哪一个是默认构造函数,以及它与其他构造函数的区别是什么?

public Module() {
   this.name = "";
   this.credits = 0;
   this.hours = 0;
}

public Module(String name, int credits, int hours) {
   this.name = name;
   this.credits = credits;
   this.hours = hours;
}
Run Code Online (Sandbox Code Playgroud)

java constructor default-constructor

147
推荐指数
7
解决办法
37万
查看次数

默认构造函数未被调用

原因:
如果一个类没有提供任何,constructors那么default constructor(constructor without parameter)在编译时由编译器给出,但如果一个类包含,parameterized constructors那么编译器不提供默认构造函数.

我正在编译下面的代码.它给出了编译错误.

代码:

class ConstructorTest
{
    // attributes
    private int l,b;

    // behaviour
    public void display()
    {
        System.out.println("length="+l);
        System.out.println("breadth="+b);
    }
    public int area()
    {
        return l*b;
    }

    // initialization
    public ConstructorTest(int x,int y) // Parameterized Constructor
    {
        l=x;
        b=y;
    }

    //main method
    public static void main(String arr[])
    {
        ConstructorTest r = new ConstructorTest(5,10);
        ConstructorTest s = new ConstructorTest();
        s.display();
        r.display();
        r.area();
    }
}
Run Code Online (Sandbox Code Playgroud)

控制台错误:

在此输入图像描述

当我只调用时parameterized constructor.它的工作正常.但是当想要调用default …

java oop constructor default-constructor

-1
推荐指数
1
解决办法
378
查看次数

标签 统计

constructor ×2

default-constructor ×2

java ×2

oop ×1