Search code examples
javavariablesprotected

Protected Access Modifier


I have the following two piece of code :

/**
 * 
 */
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);
    }

}

with the above files of code i am trying to understand purpose of protected access modifier. In the file MyUtility , I am trying to refer variable b of class MyThread.But its giving me below error:

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

My concern is variable b should be accessible from subclass as i have already extended the Mythread. But it is giving me compile time error. Also when i declare this variable as static in my superclass i was able to access it directly .So what wrong i am doing when i am trying to access via instance?


Solution

  • The method main is not explicitly part of MyThread - if you would implement another function, e.g. prtintB(), you could use the direct access with the "." operator. To access it from main you have to write a getter function.