可以在变量所在的类中定义get和set方法,来访问private变量,例如:
class Test8
{
public static void main(String[] args)
{
//定义对象
Student result=new Student("张三",22,95);
//获取get()方法
result.get();
//调用set()方法,并输出结果
Student result1=new Student();
result1.set("李二",33,99);
result1.get();
}
}
class Student
{
//定义变量
private String name;
private int age;
private float score;
//构造函数
Student(String name, int age, float score)
{
this.name = name;
this.age = age;
this.score = score;
}
Student()
{}
//set方法函数
public void set(String name1,int age1,float score1)
{
this.name=name1;
this.age=age1;
this.score=score1;
}
//get方法函数
public void get()
{
System.out.println(this.name);
System.out.println(this.age);
System.out.println(this.score);
}
}
|