package Greek;
 public class Alpha 
 { 
   protected int iamprotected;
   protected void protectedMethod() 
   { 
   System.out.println("protectedMethod");
   }
 } package Greek; 
class Gamma 

void accessMethod() 
{
Alpha a = new Alpha();
    a.iamprotected = 10; // legal 
    a.protectedMethod(); // legal 

} package Latin;
import Greek.*;
class Delta extends Alpha 

void accessMethod(Alpha a,Delta d) 
{
a.iamprotected = 10; // illegal 
    d.iamprotected = 10; // legal 
        a.protectedMethod(); // illegal 
        d.protectedMethod(); // legal 
        } 

为什么 上面的 a.iamprotected=10 和 a.protectedMethod是不合法的??而用d调用又可以??? protected,private的特点请高手说下,谢谢

解决方案 »

  1.   

    不是吧?用super就可以搞定啦,哪里用得着a
      

  2.   

    private是只能在定义的类中可以使用,其它类不能访问,比如数据库的连接对象Connection完全可以申明为private因为Connection只在数据库操作中才使用,并不能为其它类提供需求
    访问权限问题,我没有用熟,你可以去看看,权限修饰哪一块
      

  3.   

    This is a typical question.Access Modifier "protected" restricts access of an instance variables or methods to classes in the same package and subclasses outside the same package through inheritance only. As shown in your example, class Alpha and Gamma are in the same package Greek, so that "protected" instance variables and methods in class Alpha can be accessed directly using reference variable "a" of type Alpha in class Gamma.However, class Delta is in another package, so that "protected" instance variables and methods in class Alpha can NOT be accessed directly using reference variable "a" of type Alpha. Class Delta is a subclass of class Alpha, so that "protected" instance variables and methods in class Alpha can be seen as class Delta's own variables and methods, and they can be accessed directly using reference variable "d" of type Delta.
      

  4.   

    Access Modifier "private" restricts access of an instance variables or methods in the SAME CLASS ONLY.
      

  5.   

    LZ我告诉你,我调试了,不过我是放在同一个包中的,调试没任何问题,
    但是PROTECETD这个访问限制是不是对不同的包限制了不可以访问你就看看书了好,
    同个包中是可以访问的.
      

  6.   

    好象是protected的权限问题,protected允许在一个包下的类访问但不允许子类访问,Delta是Alpha的子类,当然不允许在Delta的方法中访问Alpha里的用protected 修饰的方法了
      

  7.   

    z_lping:now I understand,very thanks for your answer
      

  8.   

    protected声明的变量默认是具有包访问权限的,java有包的概念。
      

  9.   

    protected声明的,不管在哪个包,其子类都能访问,本包里如果不继承,其他类也不能访问。
    默认没有修饰的,在本包内能访问。
    private的,本类外都不能访问。 楼主的问题void accessMethod(Alpha a,Delta d) //这里的a你是通过引用的方式引入Alpha类
    {                                  //而不是继承,所以无法访问
      a.iamprotected = 10; // illegal  //d能访问是因为d继承了Alpha类
        d.iamprotected = 10; // legal  
            a.protectedMethod(); // illegal  
            d.protectedMethod(); // legal  
            }  
    }