定义NameComparator类时为什么要加上static才不报错
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | package com.imooc; public class Student { private int stuId; private String name; private int age; public Student() {} public Student( int stuId, String name, int age) { super (); this .stuId = stuId; this .name = name; this .age = age; } public int getStuId() { return stuId; } public void setStuId( int stuId) { this .stuId = stuId; } public String getName() { return name; } public void setName(String name) { this .name = name; } public int getAge() { return age; } public void setAge( int age) { this .age = age; } @Override public String toString() { // TODO Auto-generated method stub String str = "[" + "学号:" + this .stuId+ ",姓名:" + this .name+ ",成绩:" + this .age+ "]" ; return str; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class StudentTest { // 为什么这里不加static,在下方传入时会报错 public static class AgeComparator implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { // TODO Auto-generated method stub return (o1.getAge()-o2.getAge()); } } public static class NameComparator implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { // TODO Auto-generated method stub return o1.getName().compareTo(o2.getName()); } } public static void main(String[] args) { //定义三个Student类的对象及一个ArrayList类的对象 List<Student> list = new ArrayList<Student>(); Student stu1 = new Student( 40 , "peter" , 20 ); Student stu2 = new Student( 28 , "angel" , 5 ); Student stu3 = new Student( 35 , "tom" , 18 ); //将Student类的对象添加到集合中 list.add(stu2); list.add(stu3); list.add(stu1); for (Student stu:list) { System.out.println(stu); } System.out.println( "====按照name排序后====" ); //这里的new NameComparator(),如果NameComparator前面不加static会报如下错误 //No enclosing instance of type StudentTest is accessible. Must qualify the allocation with an enclosing instance of type StudentTest (e.g. x.new A() where x is an instance of StudentTest). Collections.sort(list, new NameComparator()); for (Student stu:list) { System.out.println(stu); } } } |
23
收起
正在回答
1回答
同学你好,主程序是是静态类(public static class main)。在Java中,静态类中不能直接调用动态方法。只有将内部类(AgeComparator与NameComparator)修饰为静态类,然后才能够在主方法中调用该类。所以需要添加static,将其设置为静态类。或同学也可以不将NameComparator类写在StudentTest类中进行调用。
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧