给出下面的代码段:
public class Base{int w, x, y ,z;
public Base(int a,int b)
{
x=a; y=b;
}
public Base(int a, int b, int c, int d)
{
// assignment x=a, y=b
w=d;z=c;
}}
在代码说明// assignment x=a, y=b处写入如下哪几个代码是正确的?()
A选错如果是看错了那没啥,如果不是偶然,那我解释一下:
在静态方法中(main方法就是静态方法)如果不new一个对象,或者不int,double(等八大基本数据类型加一个String)一个变量,那么必须调用静态方法或者静态变量。
public class nowCoder { public static void test() { System.out.println("test"); } public static void main(String[] args) { int a = 0; String ss = "小斌哥最帅"; test(); } }
由于构造器不是静态方法,所以不能直接调用他。
如果new了对象,或者使用八大基本数据类型,则对象或者变量没有静态要求,可以随便调。
public class nowCoder { static int a = 0; static String ss = "小斌哥~"; public void test() { System.out.println("test"); } public static void main(String[] args) { a = 11; nowCoder nc = new nowCoder(); nc.test(); } }
新手做错阔以原谅,老鸟错了就该反省了 !——!
class Test{ int x,y,z,w; public Test(int a, int b){ x = a; y = b; } public Test(int a,int b,int c,int d){ // this(a,b); 正确 new Test(a,b); //正确 x = a; //等同于this.y = a y = b; //等同于this.x = b } }