0

I Have following two classes: Test.java

package com.test.app;

public class Test {

    public int a=10;
    protected void testFunc() {
        // TODO Auto-generated method stub
        System.out.println("Test class--> testFunc");
    }
}

Another One is Main.java package com.test.main;

import com.test.app.Test;


public class Main extends Test {


    public static void main(String[] argv) {

        System.out.println("Main Method");

        Main main =new Main();
        main.testFunc(); // No Error


        Test test = new Test();
        test.testFunc(); // Error

    }

}

The method test.testFunc() from the type Test is not visible

5
  • what is the question? Commented Apr 12, 2016 at 9:24
  • 2
    Yes, that's how packages work. Commented Apr 12, 2016 at 9:25
  • That's a feature... not a bug... Commented Apr 12, 2016 at 9:28
  • I'm unable to access protected method in main method Commented Apr 12, 2016 at 9:49
  • I think stackoverflow.com/questions/16074621/… link will help you more. Commented Apr 12, 2016 at 9:55

1 Answer 1

1

The Test#testFunc() method is only accessible for sub-classes (like Main) and for classes in the same package (com.test.app).

This is why the statement

main.testFunc();

compiles fine (because Main is a sub-class of Test and it's allowed to call testFunc()).


This statement, however

test.testFunc();

doesn't compile, because the package where the Main class is located is not com.test.app, but com.test.main.

More info:

Sign up to request clarification or add additional context in comments.

3 Comments

this, especially the top comment on the accepted answer is a nice reference/proof addition to your answer :)
Yes I agree with your answer but here my question is I'm extending from super class so in this case protected methods should be available in different package ??
So in above Main class can get feature of Test class including protected method right!?? But testFunc() can not visible in Main class when I used object of Test class I.e test.testFunc()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.