class super1{
public int I = 0;
public super1 (String text){
I = 1;
}
}
public class sub1 extends super1{
public sub1(String text){
I= 2;
}
public static void main (String args[]){
sub1 sub2 = new sub1("Hello");
System.out. Println(sub2.i);
}
}What is the result?  A. Compilation will fail.  B. Compilation will succeed and the program will print “0”  C. Compilation will succeed and the program will print “1”  D. Compilation will succeed and the program will print “2”  Answer: A
   想不通, 为啥子里?

解决方案 »

  1.   


    public class sub1 extends super1{ 
    public sub1(String text){ 
    I= 2; 
    } 子类会调用父类的构造函数,在子类的构造函数的第一句,加上
    super(),因为你的父类并没有无参构造函数,所以会出现问题。
    修正:public class sub1 extends super1{ 
    public sub1(String text){ 
    super(text);
    I= 2; 
      

  2.   

    class super1{ 
    public int I = 0; 
    public super1 (String text){ 
    I = 1; 


    public class sub1 extends super1{ 
    public sub1(String text){ 
    I= 2; 
    public static void main (String args[]){ 
    sub1 sub2 = new sub1("Hello"); 
    System.out. Println(sub2.i); 


    super1里面有一个I,在sub1中没有i,肯定报错啦!在sub1中I是从什么地方来的了,你都没有声明了
      

  3.   

    或者在父类添加一个默认的构造函数class super1{ 
    public int I = 0; 
    public super1 (String text){ 
    I = 1; 
    }
    public super1 (){ 
    }

    public class Test extends super1{ 
    public Test(String text){ 
    I= 2; 

    public static void main (String args[]){ 
    Test sub2 = new Test("Hello"); 
    System.out.println(sub2.I);