2013-03-17 2 views
2

У меня есть следующие два фрагмента кода:Protected Модификатор доступа

/** 
* 
*/ 
package com.akshu.multithreading; 

/** 
* @author akshu 
* 
*/ 
public class MyThread extends Thread { 
    protected int b; 

    private int a; 
    @Override 
    public void run() { 

     super.run(); 

     System.out.println("int a:"+a); 
    } 

} 



----------- 


package com.akshu.utility; 

import com.akshu.multithreading.MyThread; 

public class MyUtility extends MyThread{ 

    public static void main(String args[]) 
    { 
     MyThread th1 = new MyThread(); 
     int d =th1.b; // line1 
     System.out.println("int d"+d); 
    } 

} 

с выше файлов кода я пытаюсь понять цель защищенного модификатора доступа. В файле MyUtility, я пытаюсь передать переменные б класса MyThread.But его давая мне ниже ошибок:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The field MyThread.b is not visibilty. 

Моего беспокойства переменных б должны быть доступны из подкласса, как я уже продлил MyThread. Но это дает мне ошибку времени компиляции. Также, когда я объявляю эту переменную статичной в моем суперклассе, я смог получить к ней доступ напрямую. Так что я делаю, когда пытаюсь получить доступ через экземпляр?

ответ

2

Метод main не является явно частью MyThread - если вы реализуете другую функцию, например. prtintB(), вы можете использовать прямой доступ с помощью "." оператор. Чтобы получить доступ к нему из основного, вам нужно написать функцию геттера.

2

Вы не можете получить доступ к защищенным свойствам из экземпляра. Вы можете обращаться к ним только в классе наследования. В этой линии-

MyThread th1 = new MyThread(); int d = th1 . b ; 

вы на самом деле пытаетесь получить доступ к защищенному свойству из экземпляра th1.

+0

OP фактически пытается получить доступ к аттестованному свойству из экземпляра 'th1'. – ShuklaSannidhya

+0

: Спасибо, я получил вашу точку. Я смешивал две разные видимости вместе. Один для примера и другой для наследования. – noone

2

Из Kathy Sierra's большой книги, объясняя непонимание protected сферы:

But what does it mean for a subclass-outside-the-package to have access to a superclass (parent) member? It means the subclass inherits the member. It does not, however, mean the subclass-outside-the-package can access the member using a reference to an instance of the superclass. In other words, protected = inheritance. Protected does not mean that the subclass can treat the protected superclass member as though it were public. So if the subclass-outside-the-package gets a reference to the superclass (by, for example, creating an instance of the superclass somewhere in the subclass' code), the subclass cannot use the dot operator on the superclass reference to access the protected member. To a subclass-outside-the-package, a protected member might as well be default (or even private), when the subclass is using a reference to the superclass. The subclass can see the protected member only through inheritance.

Таким образом, в вашем случае, вы пытаетесь использовать ссылку, чтобы получить доступ к защищенному члену вне класса пакета родителя:

MyThread th1 = new MyThread(); 
int d =th1.b; //b cannot be reached ! 
1

Спецификация Java lang раздел 6.6.2.1 скажет вам правду:

If the access is by a field access expression E.Id , where E is a Primary expression, or by a method invocation expression E.Id(. . .) , where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S .

Здесь MyThread is C, MyUtility is S и b is Id. Таким образом, в режиме MyUtility вы не можете использовать ссылку на экземпляр pf MyThread для доступа к его b

Смежные вопросы