Access private variables outside of a class in Java using comparator [duplicate]

亡梦爱人 提交于 2020-05-09 17:37:05

问题


Struggling to figure out how to access private attributes outside of a class in Java, using comparator. I'm using some code online as reference. If you change the private to public it works, but I need to know how to make it work with the variables set as private.

// Java program to demonstrate working of Comparator 
// interface 
import java.util.*; 
import java.lang.*; 
import java.io.*; 

// A class to represent a student. 
class Student 
{ 
    private int rollno; 
    private String name, address; 

    // Constructor 
    public Student(int rollno, String name, 
                            String address) 
    { 
        this.rollno = rollno; 
        this.name = name; 
        this.address = address; 
    } 

    // Used to print student details in main() 
    public String toString() 
    { 
        return this.rollno + " " + this.name + 
                        " " + this.address; 
    } 
} 

class Sortbyroll implements Comparator<Student> 
{ 
    // Used for sorting in ascending order of 
    // roll number 
    public int compare(Student a, Student b) 
    { 
        return a.rollno - b.rollno; 
    } 
} 

// Driver class 
class Main 
{ 
    public static void main (String[] args) 
    { 
        Student [] arr = {new Student(111, "bbbb", "london"), 
                        new Student(131, "aaaa", "nyc"), 
                        new Student(121, "cccc", "jaipur")}; 

        System.out.println("Unsorted"); 
        for (int i=0; i<arr.length; i++) 
            System.out.println(arr[i]); 

        Arrays.sort(arr, new Sortbyroll()); 

        System.out.println("\nSorted by rollno"); 
        for (int i=0; i<arr.length; i++) 
            System.out.println(arr[i]); 
    } 
} 

回答1:


You should create a public getter method that returns the private field value.

public int getRollno(){return this.rollno;}

And use it to access the field from outside



来源:https://stackoverflow.com/questions/61334698/access-private-variables-outside-of-a-class-in-java-using-comparator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!