Reopened topic "private protected" modifier

I respond to reply in thread <http://forums.sun.com/thread.jspa?threadID=503004>. There I posted following:
I would like to express that something like "private protected" is really missing. I develop packages for modelling of engineering structures. I have real and clear example why I need this. I was very surprised that I cannot open fields for subclasses only! Therefore I have to use "private" because I dont want to see these fields from another classes. It does not make sense in this way.
There is my example:
Imagine that there is a model for analysis of a engineering structure. This model can be 2D or 3D. Im developing three packages. First, the most abstract, contains classes useful in both 2D and 3D branches. For example class AbstractMassPoint, which has field mass. Second package is 2D brach and third package is 3D branch. In 2D and 3D branch are subclasses of AbstractMassPoint named MassPoint. I both versions of MassPoint class are relationships using mass field and one natural solution is access it directly without using getMass() method. But I like encapsulation and I dont want to see this field outside class AbstractMassPoint except subclases MassPoint which are natural subclasses. Modifier protected is too weak. I dont want to see this field in classes from package. Therefore current state is private modifier and something like getMass() methods. You can see source codes on my page (keywords: kitnarf's library, fydik).
I like Java, but this is wrong. Why it is not possible?

kitnarf wrote:
There is my example:
Imagine that there is a model for analysis of a engineering structure. This model can be 2D or 3D. Im developing three packages. First, the most abstract, contains classes useful in both 2D and 3D branches. For example class AbstractMassPoint, which has field mass. Second package is 2D brach and third package is 3D branch. In 2D and 3D branch are subclasses of AbstractMassPoint named MassPoint. I both versions of MassPoint class are relationships using mass field and one natural solution is access it directly without using getMass() method. But I like encapsulation and I dont want to see this field outside class AbstractMassPoint except subclases MassPoint which are natural subclasses. Modifier protected is too weak. I dont want to see this field in classes from package. Therefore current state is private modifier and something like getMass() methods. You can see source codes on my page (keywords: kitnarf's library, fydik).
I like Java, but this is wrong. Why it is not possible?Although you might have a case for this very specific application how does it apply to the other million possible applications that one might create? If 900,000 of them could use it in such a way that it makes the code better then it is a good idea. But if only 1 could use it then it isn't.
Given that I can get to private members if I want but it just isn't convenient to do so. So all you are doing is providing encouragement to someone to do the right thing. The best way to do that is correctly design the classes in the first place and provide correct and complete documentation. That works much better that trying to find ways to restrict it.

Similar Messages

  • Inheritance and access control - "private protected"

    I'm reopening an old topic, seems to have been last discussed here 2-3 years ago.
    It concerns the concept of restricting access to class members to itself, and its subclasses. This is what "protected" does in C++ and "private protected" did in early versions of the Java language. This feature was removed from Java with a motivation along the lines of not being "simple", and "linear" (in line with the other access modes, each being a true subset of the next). Unfortunately, the article which explained Sun's position on this keyword combination seems to have been removed from the site, so I haven't been able to read its original text.
    But regardless of simplicity of implementation or explaining Java's access modifiers to newbies, I believe it is a fundamental part of OO programming for such an access mode to exist. The arguments for having the standard "private" mode in fact also apply for having a C++-style "protected" mode. (Arguing that classes within a package are related and it therefore doesn't hurt to also give them access to Java's "protected" members, is equally arguing that "private" is unneccessary, which noone of course believes.)
    The whole concept of inheritance and polymorphism and encapsulation builds on the access modes private, protected, and public (in the C++ senses). In Java the "package" concept was added - a nice feature! But I see no justification for it to negate the proper encapsulation of a class and its specializations.

    What effect upon inheritance other than hiding members
    from subclasses is there?
    None. And I cant think of another declaration that prevents members from being inherited but private.
    Of course the onus comes on the programmer with Java's
    definition of "protected" - but
    1) there is rarely a single programmer working within
    a package
    The point was the package is a unit which does not hide from itself. Just like all methods within a class can see each other, all classes within a package can, and all packages within a program can.
    2) it muddies the encapsulation in the design - when
    you see a "protected" method someone else, or yourself
    some time ago - wrote, how do you know if the design
    intention is to have it accessed solely by the class
    and its subclasses, or if it is indeed intended to be
    shared with the whole package? The only way to do
    this today is to always explicitly specify this in the
    comments, which may be lacking, inconsistent, and
    abused (since it isn't enforced).Encapsulation would be implementation hiding. Not method hiding. The only thing you should probably allow out of your package is an interface and a factory anyway.
    I understand where you are coming from, but I really have not had occasion to take issue with it. I can't think of a real codeing situation where this is required. OTOH, I can't think of a coding situation where I need to access a protected method from another class either.

  • Interface with a protected modifier

    Can we have an interface with a protected modifier?
    For I am getting an error
    protected modifoer not allowed
    Are there any conditions where we cannot have any protected modifiers?

    Interfaces are public. For more information about interfaces please read Java Language Specification.
    /Sreenivasa Kumar Majji.
    Can we have an interface with a protected modifier?
    For I am getting an error
    protected modifoer not allowed
    Are there any conditions where we cannot have any
    protected modifiers?

  • Forcing invocation of private/protected methods

    Has anyone, any idea how can be forced the invocation of a private/protected method on a object. The client that invokes the method has a reference to the object and is declared in a different object than the targeted object.
    See code below:
    package src.client;
    import java.lang.reflect.Method;
    import src.provider.CPBook;
    public class Tester {
         public static void main(String [] args) {
              CPBook targetObj = new CPBook();
              Method [] mths = targetObj.getClass().getDeclaredMethods();
              Method targetMth = null;
              for (int i = 0; i < mths.length; i++) {               
                   if ("getMgr".equals(mths.getName())) {
                        targetMth = mths[i];
              if (targetMth != null) {
                   try {
                        Object [] obj = new Object[1];
                        obj[0] = new Boolean(true);
                        targetMth.invoke(b, obj);
                   } catch (Exception e) {                    
                        e.printStackTrace();
    package src.provider;
    public class CPBook {
         public void startDownload() {                    
         public void stopDownload() {     
         protected void getMgr(boolean bool) {
              System.out.println("------- OK ------- : " + bool);
    }Thank you.
    Best regards.

    The class java.lang.reflect.Method has a setAccessible(boolean) method on it. I think that's what you're asking for. Code that makes use of it might run into trouble if a security manager is involved, though. Generally, methods are private for a reason, too, so if your code depends on a private method, it's dependent on an implementation detail it probably shouldn't be concerned about, or even aware of

  • Private protected - ?

    I guess I haven't looked at my Java language spec in awhile (or never did very closely), but I was surprised today to find out that the "protected" specifier allows subclasses as well as any classes in the same package. I feel this is a little too much access for my tastes.
    I guess the idea here is that one developer/group will be desigining a package as a whole and will not do anything advertant or malicious with another class' protected members.
    http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
    I noticed that in Java 1.0 also had a fifth specifier as "private protected" that is no longer supported. Was this the sought-after protection that I am looking for? What was the reason for not providing something like this?
    Btw, my C++ is also a little rusty around the details, but does the "protected" specifier do the same thing with namespaces or something?

    The point of such silly code (below) is simply to demonstrate that that no one should be allowed to change the key's code except the Key. If I want to subclass a Key, I shouldn't be forced to make "Key.Code" private and re-implement Code again in my subclass. From an object-oriented perspective, I still feel that "protected" should only be valid from within sub-classes and have a 5th specifier that specifies both package and subclass.
    A colleague of mine pointed out that the "package" specifier is horizontal (across the package), but there is no specifier that is just vertical (only subclasses).
    Is there anything stopping someone to add a package to a class and compile it? For that matter, they now have access to all the protected members of the package classes.
    All classes in the same package :
    package KeyLock;
    class Lock
      public String lockCode = "MySecretKey";
      public Lock(String code)
        lockCode = code;
      protected void tryLock(Key k)
        if(k.getCode().equals(lockCode)
          System.out.println("Success");
        else
          System.out.println("Failure");
    class Key
      protected String Code = "MySecretKey";
      public String getCode()
        return Code;
      public Key()
    public class BetterKey extends Key
      public BetterKey()
        Code = "EvenBetterKey";
    class LockPicker
      public LockPicker()
        Key key1 = new Key();
        Key key2 = new BetterKey();
        Lock lock = new Lock("UselessLock");
        key1.Code = "UselessLock";
        key2.Code = "UselessLock";
        lock.tryKey(key1);
        lock.tryKey(key2);
    }Maybe I'm just spun...

  • Why should we not declare Class with protected modifier ?

    Why should we not declare Class with protected modifier ?

    jwenting wrote:
    georgemc wrote:
    Why we not research our endless questions?how else could you reach 14000 posts in under 3 years, a true achievement :) Congratulations.Ah, that reminds me. It was a long time ago since I posted some stats:
    Posts:
    jverd                        46427   2972   0,06
    DrClap                       36310   5222   0,14
    jschell                      32357   2583   0,08
    CeciNEstPasUnProgrammeur     31500   1438   0,05
    camickr                      29870   4783   0,16
    yawmark                      28729   1803   0,06
    kajbj                        24180   1829   0,08
    BalusC                       22857   2875   0,13
    warnerja                     21886   2188   0,10
    ejp                          19929   3247   0,16
    sabre150                     17537   1913   0,11
    paulcw                       16005   1724   0,11
    DrLaszloJamf                 14857   1840   0,12
    georgemc                     14000    889   0,06
    prometheuzz                  13466   1180   0,09
    cotton.m                     13409   1308   0,10
    ChuckBing                    12667   1735   0,14
    JosAH                        11926    842   0,07
    flounder                     11607   1201   0,10
    mlk                          10795    886   0,08
    Darryl.Burke                 10564   1787   0,17
    Encephalopathic              10203   1508   0,15
    tjacobs01                     9540   1658   0,17
    BigDaddyLoveHandles           8980    763   0,08
    dcminter                      8081    533   0,07
    tsith                         8049    704   0,09
    jwenting                      7831    249   0,03
    malcolmmc                     7539    819   0,11
    Michael_Dunn                  7392   2088   0,28
    PhHein                        7360   1207   0,16
    morgalr                       7081    703   0,10
    pbrockway2                    6471   1208   0,19
    BIJ001                        6179    322   0,05
    JoachimSauer                  5824    604   0,10
    abillconsl                    5777    943   0,16
    corlettk                      5671    544   0,10
    TuringPest                    5651    444   0,08
    masijade.                     5396    434   0,08
    YoGee                         4695    530   0,11
    gimbal2                       3642    315   0,09
    uncle_alice                   3496   1009   0,29
    bshannon                      3427    614   0,18
    tschodt                       3236    280   0,09
    sjasja                        3193    459   0,14
    SoulTech2012                  3005    109   0,04
    Peter__Lawrey                 2847    254   0,09
    Torgil                        2175    358   0,16
    Navy_Coder                    2119    648   0,31
    rukbat                        1951    252   0,13
    java_2006                     1913   1123   0,59
    baftos                        1808    665   0,37
    es5f2000                      1718    192   0,11
    AndrewThompson64              1716    973   0,57
    YAT_Archivist                 1713    230   0,13
    Aknibbs                       1693     86   0,05
    drvijayy2k2                   1574    266   0,17
    StanislavL                    1396   1117   0,80
    stefan.schulz                 1159    208   0,18
    JayDS                         1100    410   0,37
    dannyyates                    1094    211   0,19
    Joerg22                       1046     48   0,05
    uj_                           1033     49   0,05

  • Difference between 'default' and 'protected' modifier

    Hello!
    Whats the difference between 'default' and 'protected' modifier?
    Thank you!

    Explanation here
    http://www.webchalkboard.com/java/tute6.shtml

  • Private, protected Access Modifiers with a class

    Why cant we use private and protected access modifiers with a class?
    Thanks.

    Matiz wrote:
    >
    Public access allows you to extend a parent class in some other package. If you only want users to extend your class rather than instantiate it directly, make the class abstract and design for extension.Agreed. However, would the same argument be not true for the default access at the class level? No. Default access would only allow you to extend a parent class in the same package (as opposed to some other package).
    Now my confusion is why is a class allowed default access at the top level and not protected?Because protected for a top-level class makes no sense. The protected keyword provides member access to any other class in the same package and extending classes outside the package. A top-level class isn't a member of a class, by definition, so there's nothing that protected would do provide differently than public.
    So, the two access modifiers for a top-level class are public and default. Public allows access to the class outside the package, whereas default restricts access to the class within the package.
    ~

  • Private access modifier

    is it best programming practice to always define my class variables as private ?
    Or should I just leave them as the default internal ?
    I notice on most code examples they are just left as internal default.
    Thanks

    declaring provate variable is always good as long as you dont need to restrict the scrope at maximum level.
    providing setter method for private member is like exposing to outer world.
    so, unless you need to change private variable value, you can use public/protected getter but setter with care!

  • Applying Private & Protected methods inside JSP

    I am trying to apply (or copy) codings from Servlet into JSP.
    One of the issue that I encountered was bringing Private and Protected methods that were listed inside the Servlet class (this case: public abstract class CatalogPage).
    If I only copy everything inside "Public void doGet", JSP would not work.
    1) My question is, is it better approach to apply Private and Protected method beside wrapping around with ( <%! %> (with !)) (like below)?
    I think I heard about using " ! " for private methods somewhere in the internet..
    Here is what I have at JSP.
    <%!
    Private CatalogItem[] items;
    Private String[] itemIDs;
    private String title;
    protected void setItems(String[] itemIDs) {
    protected void setTitle(String title) {
    %>
    <%
    if (items == null) {
    response.sendError(response.SC_NOT_FOUND,
    "Missing Items.");
    return;
    %>
    2) Is there any other ways I could make the functionality of Private and Protected methods
    work inside the JSP's <% %>?
    Thank you.
    Here is the original Servlet code.
    public abstract class CatalogPage extends HttpServlet {
      private CatalogItem[] items;
      private String[] itemIDs;
      private String title;
      protected void setItems(String[] itemIDs) {
        this.itemIDs = itemIDs;
        items = new CatalogItem[itemIDs.length];
        for(int i=0; i<items.length; i++) {
          items[i] = Catalog.getItem(itemIDs);
    protected void setTitle(String title) {
    this.title = title;
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    if (items == null) {
    response.sendError(response.SC_NOT_FOUND,
    "Missing Items.");
    return;
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType =
    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
    "Transitional//EN\">\n";
    out.println(docType +
    "<HTML>\n" +
    "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
    "<BODY BGCOLOR=\"#FDF5E6\">\n" +
    "<H1 ALIGN=\"CENTER\">" + title + "</H1>");
    CatalogItem item;
    for(int i=0; i<items.length; i++) {
    out.println("<HR>");
    item = items[i];
    // Show error message if subclass lists item ID
    // that's not in the catalog.
    if (item == null) {
    out.println("<FONT COLOR=\"RED\">" +
    "Unknown item ID " + itemIDs[i] +
    "</FONT>");
    } else {
    out.println();
    String formURL =
    "/servlet/coreservlets.OrderPage";
    // Pass URLs that reference own site through encodeURL.
    formURL = response.encodeURL(formURL);
    out.println
    ("<FORM ACTION=\"" + formURL + "\">\n" +
    "<INPUT TYPE=\"HIDDEN\" NAME=\"itemID\" " +
    " VALUE=\"" + item.getItemID() + "\">\n" +
    "<H2>" + item.getShortDescription() +
    " ($" + item.getCost() + ")</H2>\n" +
    item.getLongDescription() + "\n" +
    "<P>\n<CENTER>\n" +
    "<INPUT TYPE=\"SUBMIT\" " +
    "VALUE=\"Add to Shopping Cart\">\n" +
    "</CENTER>\n<P>\n</FORM>");
    out.println("<HR>\n</BODY></HTML>");
    null

    I am trying to apply (or copy) codings from Servlet into JSP.What benefit is there to copying code from a servlet to a JSP? Is the servlet "working"?
    One of the issue that I encountered was bringing
    Private and Protected methods that were listed inside
    the Servlet class.
    If I just copy everything inside "Public void doGet",
    JSP would not work.Sounds like you need a redesign.
    1) My question is, is it better approach to apply
    Private and Protected method beside wrapping around
    with ( <%! %> (with !)) (like below)?
    I think I heard about using " ! " for private
    methods somewhere in the internet..Never heard of such a thing. Please cite the link if you have it.
    Here is what I have at JSP.Please, I can't look. This is wrong on so many levels. You've got scriptlet code, CSS style stuff, embedded HTML in one unmaintainable mess.
    Learn JSTL and CSS. Do not, under any circumstances, put scriptlet code in your JSP.
    The right way is to use the JSP purely as display and keep those protected and private methods on the server side where they belong. Have the JSP make a request to another object to do some work, get the result, and displa it.
    %

  • Inheritance: public, private, protected & default?

    I have a good idea where, and when, to use public, private and protected, but what is the default used for? By default I mean just not specifing the inheritance.
    Ex:
    String aString;
    Thanks in advance,
    Brian

    It means basically that only classes written to the same package as that one, would be able to access the member, regardless of whether they inherit from the class or not. If a class inherits from it, but is not written in the same package, it cannot access the member - it's just as if it were written as "private" in that case.

  • Private, protected advantages, disadvantages

    Hi,
    Is there a significant difference between private and protected instead of the sight in the package?
    The question is cause of the often usage of protected in "official" code instead of private.
    regards
    Olek

    Navy_Coder wrote:
    Olek wrote:
    Hi,
    Is there a significant difference between private and protected instead of the sight in the package?
    The question is cause of the often usage of protected in "official" code instead of private.
    regards
    Olek??? What do you mean by "official" code? I write "official" code (or so I thought any way) and I use significantly more private variables than protected.Me too. I tend to follow the doctrine that a variable should be private unless there is a good reason for it not to be. I always restrict access as far as seems reasonable, and rarely ever use protected variables. I find there are very few examples of times I think I need access to a super class's data members. On occasion, I will use protected methods or protected constructors, but there again, if I don't need them to be protected, I'm definitely going to make them private, instead.
    - Adam

  • Static, public, private, protected?

    Sorry for these questions, but I still don't know why properly why you use static, prublic, protected?
    And also is it possible to have a multi array first bit being and short and second being a byte e.g.
    int item_id[] byte[]so item_id[0][0] = 5
    first 0 means you got nothing on
    second 0 is the hp stat
    = 5 adds 5 hp onto the total is this possible

    Morpher wrote:
    Sorry for these questions, but I still don't know why properly why you use static, prublic, protected?No problem, that's how you learn.
    Look at this and this .
    And also is it possible to have a multi array first bit being and short and second being a byte e.g.Why would you want to do that? If you feel like using wrapper classes, you can make an array of Objects.

  • Do java programms after giving compilation error generates .class file?

    Do java programms after giving compilation error generates the .class file?
    Do any outer class may have the private as access modifier?
    If someone asks you that -do any program in java after giving a compilation error gives the .class file -do any class except(inner class)
    be defined as private or static or protected or abc or xxx Now type the
    following program
    private class test
    public static void main(String s[])
    System.out.println("Hello!How are You!!");
    -Compile it.... You must have
    received this error test.java:1:The type type can't be private. Package members are always accessible within the current package. private class
    test ^ 1 error
    Here please notify that compiler has given the
    error not the warning therfore .class file should not be created but now type
    >dir *.class
    ___________ and you will see that the
    test.class file existing in the directory nevertheless this .class file
    is executable. if you will type __________________ >java test
    it will
    wish you Hello! and suerly asks you that How are You!! ________________!
    You can test it with the following as acces modifiers and the progrm will run Ofcourse it will give you compilation error.
    protected
    xxx
    abc
    xyz
    private
    Do you have any justification?

    Hmm,
    I've been working with different versions of jdk since, if I'm not mistaken, jdk1.0.6 and never was able to get *.class with compilation errors. It was true for Windows*, Linux, and Solaris*.
    About the 'private'/'protected' modifier for the type (class) - it makes perfect sence not to allow it there: why would anyone want to create a type if no one can access it? There should be a reason for restricting your types - let's say, any inner class can be private/protected.
    For ex., you shouldn't have compile problems with this:
    class Test
    public static void main(String s[])
    System.out.println("Hello!How are You!!");
    private class ToTest{}
    Sorry, but I don't really know where you can read up on that.

  • Can java have Protected or Private Constructor

    Hi,
    can java have Priavte or protected constructor,
    as we know java have default and public constructor ,
    and in using singleton design patters we can use private & protected constructor,
    so, what is the main logic,
    Regards,
    Prabhat

    Hi,
    Yes, We can declare constructor as private/public/protected also.
    Having only private constructors means that you can't instantiate the class from outside the class (although instances could still be created from within the class - more about this later). However, when you instantiate a class, you must first initialize all superclasses of that class by invoking their constructors. If one of the superclasses has only private constructors declared, we have a problem. We can't invoke the superclass' constructor which means that we can't instantiate our object. Because of this, we've essentially made a class that can't be extended.
    example:
    class TheWorld
    private static TheWorld _instance = null;
    private TheWorld() {}
    public static TheWorld instance()
    if ( _instance == null )
    _instance = new TheWorld();
    return _instance;
    public void spin() {...}
    public class WorldUser
    public static void main(String[] args)
    TheWorld.instance().spin();
    }

Maybe you are looking for

  • How do I keep my library settings the same after importing?

    Hi. I have organized my whole itunes library down to the gritty upper/lowercase characters of the song names (due to my compulsive nature), and want to keep all my settings for later on when i backup my information as well as import it in the future.

  • Access to WAN Port 2 on an CISCO ISA 550 Firewall

    Hi all On a CISO ISA 550 Firewall i created a 2 WAN Port Failover whichs works fine. But how can access the WAN2 Port (see Attaments) from my Workstation even the WAN1 Port is up an runnig, i created also a new Zone and Firewall Rule but this dosen't

  • Oracle to SAP BI with BCS u2013 Best Data flow Design.

    Hi,   We are a SAP implementation team. We are @ Blue Print stage. My client is a RETAIL Business Gaint. Client has 50 % of Transaction data and Master data in Oracle data base. Now we are moving to BI 7.0 and also has plans to use SAP-BCS.   We woul

  • Openscript / web document

    Hello, please I have a question : web:document what is the web document ? because I understand the web:window which is the browser, td etc. but I dont know to which object it refers to (the document). thank you. Michael

  • Can't see objects from all db schemas in AV when creating a FGA Policy

    Hi all, I have installed Audit Vault successfully but when I try to create a FGA policy, in the Object field the objects from certain schemas don't appear in the list. I tried to verify if the user that the Agent uses to connect to the source databas