一个类可以没有构造函数吗? [英] Can a class have no constructor?
本文介绍了一个类可以没有构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一段代码作为一个例子,其余的只是方法(看迷宫类的底部)。因此,当实例化时,使用
This is a piece of code as an example, after this rest are just methods (look at bottom for maze class). So when this is instantiated, using
Maze labyrinth = new Maze();
和
System.out.println (labyrinth);
这将打印出网格数组。
这是合法的吗?我认为所有类都需要构造函数如何打印2-d网格数组?
This will print out the grid array. Is this legit? I thought all classes needed constructors how does it print out the 2-d grid array?
迷宫类:
public class Maze
{
private final int TRIED = 3;
private final int PATH = 7;
private int[][] grid = { {1,1,1,0,1,1,0,0,0,1,1,1,1},
{1,0,1,1,1,0,1,1,1,1,0,0,1},
{0,0,0,0,1,0,1,0,1,0,1,0,0},
{1,1,1,0,1,1,1,0,1,0,1,1,1},
{1,0,1,0,0,0,0,1,1,1,0,0,1},
{1,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1,1,1,1,1} };
public String toString ()
{
String result = "\n";
for (int row = 0; row < grid.length; row++)
{
for (int column=0; column < grid[row].length; column++)
result += grid[row][column] + "";
result += "\n";
}
return result;
}
}
推荐答案
显式定义构造函数不是必需的;但是,所有类都必须有一个构造函数,如果你不提供任何类,将生成一个默认的空构造函数:
It is not required to explicitly define a constructor; however, all classes must have a constructor, and a default empty constructor will be generated if you don't provide any:
public Maze() {
}
参见默认构造函数。
这篇关于一个类可以没有构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文