public class Base {
public static void main(String[] args) {
Derive d = new Derive();
}
private int i;
public Base(int i) {
this i = i;
}
class Derive extends Base{
private int j;
}
}
1、Base有参构造器中应该是 this.i = i;
2、子类Derive应该写在Base类下边不是内部
3、由于创建Derive是用的无参构造器,所以需要重写Base和Derive的无参构造器方法
修改后代码如下:
public class Base {
public static void main(String[] args) {
Derive d = new Derive();
}
private int i;
public Base() {
}
public Base(int i) {
this.i = i;
}
}
class Derive extends Base {
private int j;
public Derive() {
}
}
第7行 this i=i是啥
1.父类只有一个有参构造方法,子类也必须有一个有参构造方法
2.成员内部类需要通过父类实例引用
public class Base {
public static void main(String[] args) {
Derive d=new Base(1).new Derive(1);
}
private int i;
public Base(int i) {
this.i = i;
}
class Derive extends Base{
private int j;
public Derive(int i) {
super(i);
}
}
}
【面试】五分钟掌握内部类(静态内部类、成员内部类、方法内部类、匿名内部类) http://t.csdn.cn/EPP93
Derive类需要用static修饰才行。原因很简单,虽然你是new了Derive对象,但是本质上Derive也是Base类的一个变量,即使它是一个类,所以在静态方法中使用这个变量,那么这个变量也必须是静态的
public class Person {
public static void main(String[] args) {
Derive d = new Derive(1);
}
private int i;
public Person(int i) {
this.i = i;
}
}
class Derive extends Person {
private int j;
public Derive(int i) {
super(i);
}
}
不过这么写很不规范