构造方法重载,而只调用一个构造方法。其他的还有什么作用?
就拿下面的代码举个例子:
public class TestNode {
public static void main(String[] args) {
Node head = null;
for(int i=0; i < 5; i ++) {
String str = String.valueOf(i);
head = new Node(str, head);
}
while(head != null) {
System.out.println(head.value);
head = head.next;
}
}
}class Node extends Object {
Object value;
Node next;
Node() {
value = null;
next = null;
}
Node(Object value, Node next) {
this.value = value;
this.next = next;
}
}
这里无参数的构造方法Node()有什么作用?把它注掉该程序也可以运行,结果和未注掉是一样的!
就拿下面的代码举个例子:
public class TestNode {
public static void main(String[] args) {
Node head = null;
for(int i=0; i < 5; i ++) {
String str = String.valueOf(i);
head = new Node(str, head);
}
while(head != null) {
System.out.println(head.value);
head = head.next;
}
}
}class Node extends Object {
Object value;
Node next;
Node() {
value = null;
next = null;
}
Node(Object value, Node next) {
this.value = value;
this.next = next;
}
}
这里无参数的构造方法Node()有什么作用?把它注掉该程序也可以运行,结果和未注掉是一样的!
Node() {
value = null;
next = null;
} 只是你把构造方法内的变量或称属性都初始化为空当然你就感觉没什么影响呀,你不然自己另写一个构造方法的程序,不要初始化为空试试看
public class Test {
static String value = null;
Test(){
value = "aaa";
}
public static void main(String[] args) {
new Test();
System.out.println(Test.value);
}
}用不用new Test()结果都是null?还是我理解错了?
哈哈,有趣!构造方法的作用:
1.创建新对象;
2.将新对象的属性初始化。
-----------------------
你的程序这段确实没什么用:
Node() {
value = null;
next = null;
}
-----------------------
java的编译器如果检测到你没有在java源代码中添加构造函数就会添加一个午参数且没有执行语句构造函数例如你的Node类中没写构造函数,编译时就会为你自动添加一个Node(){}构造函数,如果编译器检测到你的java代码中有构造函数就不会添加了,所以你如果写了一个带参数的构造函数,编译器就不会再添加无参数构造函数,如果你需要无参数构造函数就要自己手动再添加上去。还有,构造方法是在构造对象之后执行的,构造方法并不负责构建对象,从它的作用上来说是用来初始化对象的,它在构建对象后立即执行,且构造方法不负责构建对象,只是它在构建对象之后立即执行而已。
class A {
A(int a) {
}
}class B extends A {
}class Test {
public static void main(String[] args) {
// 声明一个B对象并且对其初始化时,因为B类继承自A类,所以首先会构造一个A()的对象。
// 如果A中没有无参构造,则程序出现问题。
// 此时情况出错!因A(int a)没有被调用!
// 那么只要在A类中显示定义一个A(){}就OK了!
B a = new B();
}
}
next = null; 这个没什么用,因为本来它的默认值就是null但是public Node() {
}就有用了,没了它你就没办法构建无参对象了(因为你已经写了一个有参的构造方法)
如果是继承的话,子类有构造方法能给父类通过对象引用而得,也不失为一种好方法。这也是编程的习惯!