开发者

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 meth开发者_开发知识库od 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜