访问权限

(1)私有变量和私有方法

对于私有成员变量或方法,只有在本类中创建该类的对象时,这个对象才能访问自己的私有成员变量和类中的私有方法。

class Example4_14
{
 private int money;
 Example4_14()
 {
  money = 2000;
 }
 private int getMoney()
 {
  return money;
 }
 public static void main(String args[])
 {
  Example4_14 exa = new Example4_14();
  exa.money =3000;
  int m = exa.getMoney();
  System.out.println("money = "+m);
 }

F:/javacode>java Example4_14
money = 3000

 

(2)共有变量和共有方法

class Tom
{
 public float weight;
 public float f(float a,float b)
 {
  …… ……
 }
}

在任何一个类中用类Tom创建一个对象后,该对象能访问自己的public变量和类中的public 方法

class Jerry
{
 void g()
 {
  Tom cat = new Tom();
  cat.weight = 23f;  //合法
  cat.f(3,4);  //合法
 }
}

(3) 友好变量和友好方法

class Tom
{
  float weight;  //weight是友好的float变量
  float f(float a,float b) //方法f是友好方法
  {
  …… ……
  }
}

Jerry和Tom是同一包中的类,那么

class Jerry
{
 void g()
 {
  Tom cat = new Tom();
  cat.weight = 23f;  //合法
  cat.f(3,4);  //合法
 }
}

(4)受保护的成员变量和方法

class Tom
{
 protected float weight;
 protected float f(double a,double b);
 {
   ......
 }
}

Jerry和Tom是同一包中的类
class Jerry
{
 void g()
 {
  Tom cat = new Tom();
  cat.weight = 23f; //合法
  cat.f(3,4);  //合法
 }
}

(5)public类和友好类

public 类

public class A

{     ......

}

友好类

class A

{  ......

}   //在另外一个类中,使用友好类中创建对象时,要保证他们在同一个包中

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值