使用比较器访问Java类外部的私有变量 [英] Access private variables outside of a class in Java using comparator

查看:107
本文介绍了使用比较器访问Java类外部的私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

努力弄清楚如何使用比较器在Java类之外访问私有属性.我在网上使用一些代码作为参考.如果您将private更改为public,那么它可以工作,但是我需要知道如何使用设置为private的变量来使其工作.

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]); 
    } 
} 

推荐答案

您应该创建一个公共的getter方法,该方法返回私有字段值.

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

这篇关于使用比较器访问Java类外部的私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆