Java私有变量、共有变量、友好变量的用法-详解
1、首先介绍访问权限的概念:
访问权限是对象是否可以通过‘.’运算符操作自己的变量或通过‘.’运算符操作类中的方法。
访问权限修饰符有private、protected、public。都是java的关键字。
public static void main(String[] args){
System.out.println("My qq id is : 3109683646");
System.out.println("There are many useful information about the java and the python program.");
}
2、私有变量和私有方法:
用private修饰的成员变量和方法称为私有变量和私有方法:
class Person{
private double weight; //weight 是private的double型变量
private double f(double a,double b)
{
return a+b; //f是private方法
}
}
在另外一个类中用Person类创建的对象不能访问自己的私有变量和私有方法。
class Infomation{
Person info = new Person();
info.weight = 90.2f; //ERROR
double sum = info.f(11.0,12.0); //ERROR
}
另外注意:
如果一个类中的某个成员是私有的类成员或私有的类方法,那么在另外一个类中不能调用那个类的私有类成员和私有类方法。
private static int iAge;
private static double getAge()
3、共有变量和共有方法:
用public修饰的成员变量和方法称为共有变量和共有方法:
class Person{
public double weight; //weight 是public的double型变量
public double f(double a,double b)
{
return a+b; //f是public方法
}
}
在另外一个类中用Person类创建的对象能访问自己的共有变量和共有方法。
class Infomation{
Person info = new Person();
info.weight = 90.2f; //RIGHT
double sum = info.f(11.0,12.0); //RIGHT
}
另外注意:
如果一个类中的某个成员是public的类成员或public的类方法,那么在另外一个类中可以使用类名Person来操作那个类中的public类成员和public类方法。
public static int iAge; //public类变量
public static double getAge() //public类方法
Person.iAge = 10; / / 直接使用类名来访问public类变量
Person.getAge(); // 直接使用类名来访问public类方法
4、友好变量和友好方法:
不用private、protected、public 修饰符的成员变量和方法称为友好变量和友好方法。
class Person{
double weight; //weight 是友好的double型变量
double f(double a,double b)
{
return a+b;
}
}
在另外一个类Information中用Person类创建一个对象后,如果这个类与Person类在同一个包中,那么该对象可以访问自己的友好变量和友好方法。
class Infomation{
Person info = new Person();
info.weight = 90.2f; //RIGHT
double sum = info.f(11.0,12.0); //RIGHT
}
在任何一个与Person同一个包的类中,可以通过类名访问类友好变量和类友好方法。
static int iAge; //类友好变量
static double getAge() //类友好方法
Person.iAge = 10; / / 直接使用类名来访问类变量
Person.getAge(); // 直接使用类名来访问类方法
5、受保护的成员变量和方法:
用protected修饰的成员变量和方法被称为受保护的成员变量和方法。
class Person{
protected double weight; //weight 是友好的double型变量
protected double f(double a,double b)
{
return a+b;
}
}
如果另一个类Information与Person类在同一个包中,那么在infomation类中创建的对象可以访问protected变量和protected方法。
另外,如果两个类在同一个包中,则可以通过类名访问protected类变量和protected类方法。
class Infomation{
Person info = new Person();
info.weight = 90.2f; //RIGHT
double sum = info.f(11.0,12.0); //RIGHT
}