鱼C论坛

 找回密码
 立即注册
查看: 2732|回复: 5

对象数组的题目

[复制链接]
发表于 2020-5-19 20:13:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 910631286 于 2020-5-19 20:28 编辑
  1. package demo1;
  2. public class StudentText {
  3.         public static void main(String[] args) {
  4.                 Student[] stus=new Student[20];
  5.                 for (int i = 0; i < stus.length; i++) {
  6.                         stus[i] = new Student();
  7.                         stus[i].number=(i+1);
  8.                 }
  9.         }
  10.         class Student{
  11.                 int number;
  12.                 int state;
  13.                 int score;
  14.         }

  15. }
复制代码

为什么这一行会报错stus = new Student();
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-5-19 20:16:19 | 显示全部楼层
报错为No enclosing instance of type StudentText is accessible. Must qualify the allocation with an enclosing instance of type StudentText (e.g. x.new A() where x is an instance of
StudentText).
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-19 20:17:18 | 显示全部楼层
是不是上面的public少了个p的原因?你补上试试
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-5-19 20:30:20 | 显示全部楼层
qiuyouzhi 发表于 2020-5-19 20:17
是不是上面的public少了个p的原因?你补上试试

这个是我复制的时候不小心删的,加上也是报错
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-20 10:06:40 | 显示全部楼层
本帖最后由 dq756620245 于 2020-5-20 10:09 编辑

请楼主了解一下Java内部类的正确实例化方式,你先要StudentText studentText = new StudentText();  然后StudentText.Student stus = studentText.new Student();
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-5-20 11:12:44 | 显示全部楼层
main方法是静态的,而Student内部类是动态的,你把Student类加上static修饰就可以了。
如果你不想加static修饰可以先new一个StudentText对象出来,再通过这个对象把内部类的对象new出来
  1. public class StudentText  {
  2.         public static void main(String[] args) {
  3.                 Student[] stus=new Student[20];
  4.                 StudentText t= new StudentText();
  5.                 for (int i = 0; i < stus.length; i++) {
  6.                         stus[i] = t.new Student();
  7.                         stus[i].number=(i+1);
  8.                 }
  9.         }
  10.          class Student{
  11.                 int number;
  12.                 int state;
  13.                 int score;
  14.         }
  15. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-18 14:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表