* 构造函数问题
* 构造函数举例
在eclipse中输出结果为:
*********************
1, 2
*********************
* 构造函数组成
* 访问控制符必须是非私有(即非private)
* 可以一个也可以多个
* 可以有参也可以无参
* 函数名必须和类名一致
* 最好是无返回值的
* 如果一个类中定义了多个构造函数, 那么可以使用一个构造函数 也可以使用多个构造函数
* 如果类中没有定义构造函数(或者定义的构造函数为无参的), 而你却在新建对象时加入参数, it's error.
* 当你没有在类中定义构造函数,那么编译器会认为新建对象时不需要参数,
在eclipse中输出结果为:
****************
0 0
***************
* 构造函数举例
class A {
int i;
int j;
// 构造函数
public A(int a, int b) {
i = a;
j = b;
System.out.printf("%d %d\n", i, j);
}
}
class Test {
public static void main(String[] args) {
A aa = new A(1, 2); // 因为此刻class A中有构造函数, 并且构造函数需要两个参数, 所以可以直接赋值
//A aa2 = new A(); //error, 因为此刻class A中构造函数需要两个参数
}
}
在eclipse中输出结果为:
*********************
1, 2
*********************
* 构造函数组成
* 访问控制符必须是非私有(即非private)
* 可以一个也可以多个
* 可以有参也可以无参
* 函数名必须和类名一致
* 最好是无返回值的
* 如果一个类中定义了多个构造函数, 那么可以使用一个构造函数 也可以使用多个构造函数
class A {
int i;
int j;
// 构造函数(有参)
protected A(int a, int b) {
i = a;
j = b;
System.out.printf("%d %d\n", i, j);
}
//构造函数(无参)
public A() {
System.out.printf("哈哈");
}
public void f() {
System.out.printf("嘿嘿");
}
}
class text {
public static void main(String[] args) {
A aa = new A(1, 2);
//A aa2 = new A();
aa.f();
//aa2.f();
}
}
* 如果类中没有定义构造函数(或者定义的构造函数为无参的), 而你却在新建对象时加入参数, it's error.
* 当你没有在类中定义构造函数,那么编译器会认为新建对象时不需要参数,
class A {
int i;
int j;
}
class text {
public static void main(String[] args) {
A aa = new A(1, 2); //error
A aa = new A(); //it's OK
}
}
* 构造函数
class A {
private int i;
private int j;
public void f () {
System .out.printf("%d %d\n", i, j);
}
// 构造函数
//public A(int k, int m) { //注意:构造函数的函数名必须和class 名一致
// i = k;
// j = m;
// System.out.printf("%d %d\n", i, j);
// }
}
class text {
public static void main(String[] args) {
A aa = new A();
aa.f();
}
}
在eclipse中输出结果为:
****************
0 0
***************