简体   繁体   中英

Declare Class Attribute Protected or Public?

I have a class say within a package com.practise.mypackageone.MyClass

Class MyClass has a method

 /* Modifier  */ void show()
{
 // some code here
}

I want this method to be only accessible from another package class say

com.practise.mypackagesecond.SecondClass

Now if I made the method public it will accessible to everywhere which I dont want. and if I made it protected then SecondClass has to extend MyClass in order to access it.

But any other package class can also extend my class to access that method.

How can I prevent that?

Put the classes in the same package and make the method package private(the default modifier). Otherwise I think what you want is not achievable.

The classes in the 1st package can extend a class from the 2nd package that looks like this, and they can implement the show() method as they wish:

    public static abstract class Showable {
        abstract protected void show();
    }

If there is only one class in the 2nd package (say, ViewManager) that needs to call this method you might want to embed this Showable in it so that only this class can call the show() method.

It is not a very clean design though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM