有段时间没有接触Java了,最近重新拾起,在练习中遇到了下面问题:
package com.demo.first;
public class First {
public class Star {
private String name;
private int age;
private String team;
private String position;
public Star(String name, int age, String team, String position){
this.name=name;
this.age=age;
this.team=team;
this.position=position;
}
public void getInfo() {
System.out.println("The star's information is as follows:"+this.name+this.age+this.team+this.position);
}
}
public class Superstar extends Star{
private String[] awards;
private String name;
private int age;
private String team;
private String position;
public Superstar(String name, int age, String team, String position,String[] awards) {
super(name, age, team, position);
int length=awards.length;
awards=new String[length];
for(int i=0;i<length;i++) {
this.awards[i]=awards[i];
}
}
public void getInfo() {
System.out.println("The superstar's information is as follows:"+this.name+this.age+this.team+this.position);
for(int i=0;i<awards.length;i++) {
System.out.println(i+"."+awards[i]);
}
}
}
public static void main(String[] args) {
Star rookie=new Star("Ben Simons", 21, "76ers","Small Forward");//报错
}
}
在主函数中语句
Star rookie=new Star("Ben Simons", 21, "76ers","Small Forward");//报错
错误提示为:
No enclosing instance of type First is accessible. Must qualify the allocation with an enclosing instance of type First (e.g. x.new A() where x is an instance of First).
翻译过来就是
无法访问类型为First的外围实例。必须使用First类型的外围实例(例如x . new A ( ) )限定分配,其中x是First的实例。
解决方法:将Star和Superstar这两个类声明为静态
package com.demo.first;
public class First {
public static class Star {
private String name;
private int age;
private String team;
private String position;
public Star(String name, int age, String team, String position){
this.name=name;
this.age=age;
this.team=team;
this.position=position;
}
public void getInfo() {
System.out.println("The star's information is as follows:"+this.name+this.age+this.team+this.position);
}
}
public static class Superstar extends Star{
private String[] awards;
private String name;
private int age;
private String team;
private String position;
public Superstar(String name, int age, String team, String position,String[] awards) {
super(name, age, team, position);
int length=awards.length;
awards=new String[length];
for(int i=0;i<length;i++) {
this.awards[i]=awards[i];
}
}
public void getInfo() {
System.out.println("The superstar's information is as follows:"+this.name+this.age+this.team+this.position);
for(int i=0;i<awards.length;i++) {
System.out.println(i+"."+awards[i]);
}
}
}
public static void main(String[] args) {
Star rookie=new Star("Ben Simons", 21, "76ers","Small Forward");
}
}