java - Why cant we have multiple compareTo functions in a class like we can have multiple compare functions? -
import java.util.comparator; class pupil implements comparable<student> { private int rn; private float cg; private string name; public student(int num, float cgpa, string nm) { rn = num; cg = cgpa; name = nm; } public int getrn() { homecoming rn; } public float getcg() { homecoming cg; } public string getname() { homecoming name; } public static class orderbyrn implements comparator<student> { @override public int compare(student obj1, pupil obj2) { homecoming obj1.rn>obj2.rn? 1 : (obj1.rn<obj2.rn? -1 : 0 ); } } public static class orderbycg implements comparator<student> { @override public int compare(student obj1, pupil obj2) { homecoming obj1.cg>obj2.cg? 1 : (obj1.cg<obj2.cg? -1 : 0 ); } } /* note fails compile! public static class testingcomparable implements comparable<student> { @override public int compareto(student obj) { homecoming cg>obj2.cg? 1 : (cg<obj2.cg? -1 : 0 ); } } */ @override public int compareto(student obj2) //while overriding types have compatible ie either same or related inheritance { homecoming rn>obj2.rn? 1 : (rn<obj2.rn? -1 : 0 ); } public string tostring() { homecoming rn+name+cg; } }
the error displayed : "non-static variable cg cannot referenced static context" stuck. help much appreciated. thanks. pardon me if not clear enough. first time posting question! :d
it fails because referencing cg field of student class within nested static class testingcomparable - can't see instance fields of student class. orderbycg works becuase references cg fields on objects obj1 , obj2.
java comparator comparable
No comments:
Post a Comment