Private attributes and Inheritance.

I have a question regarding 'private attributes and inheritance'.
If I have a class that will be extended by other classes,(basically
this will act as a BASE class ),then why do I need to define
any attribute private to this base class.?
If I define an attribute as private in the base class,then the subclass cannot access
this attribute.Right?
1) Why define a private attribute in the base class ?
2) When can a situation arise whereby the base class attribute is defined
as 'private' and the base class is also extensible?

If I define an attribute as private in the base
class,then the subclass cannot access
this attribute.Right?Right. A simple example would tell you this.
>
1) Why define a private attribute in the base class?Because information hiding and encapsulation are always good things, even between super and sub classes.
>
2) When can a situation arise whereby the base class attribute is defined
as 'private' and the base class is also extensible?This question makes no sense whatsoever. A base class is extensible, unless it is marked as final, whether or not it's got private data members.
Objects usually have private state and public interfaces. The idea is that clients of a class, even subclasses, should only access the private state thorugh the public interface. So if you've designed your classes properly you shouldn't need to access that private state.
If you do, you can always provide get/set methods.
OR declare the data members as protected. That way they're package visible and available to subclasses.
But private members do not make a class inextensible.
%

Similar Messages

  • Problem with local class, static private attribute and public method

    Hello SDN,
    Consider the following situation:
    1) I have defined a LOCAL class airplane.
    2) This class has a private static attribute "type table of ref to" airplane (array of airplanes)
    3) A public method should return the private static table attribute
    Problems:
    a) The table cannot be given as an EXPORTING parameter in the method because TYPE TABLE OF... is not supported and I get syntax errors. I also cannot define a dictionary table type because it is a local class.
    b) The table cannot be given as a TABLES parameter in the method because TABLES is not supported in the OO context.
    c) The table cannot be given as an EXPORTING parameter in the method defined as LIKE myStaticAttribute because my method is PUBLIC and my attribute is PRIVATE. ABAP syntax requires that all PUBLIC statements are defined before PRIVATE ones, therefore it cannot find the attribute to reference to with LIKE.
    I see only 2 solutions:
    a) Never ever use local classes and always use global classes so that I might define a dictionary table type of my class which I can then use in my class.
    b) Make the attribute public, but this goes against OO principles, and isn't really an option.
    Am I missing anything here, or is this simply overlooked so far?

    Hello Niels
    Since your class is local and, thus, only know to the "surrounding" application is does not really make sense to make it public to any other application.
    However, if you require to store instances of your local classes in internal tables simply use the most generic reference type possible, i.e. <b>OBJECT</b>.
    The following sample report shows how to do that. Furthermore, I believe it also shows that there are <u><b>no </b></u>serious inconsistency in the ABAP language.
    *& Report  ZUS_SDN_LOCAL_CLASS
    REPORT  zus_sdn_local_class.
    " NOTE: SWF_UTL_OBJECT_TAB is a table type having reference type OBJECT
    *       CLASS lcl_airplane DEFINITION
    CLASS lcl_airplane DEFINITION.
      PUBLIC SECTION.
        DATA:    md_counter(3)             TYPE n.
        METHODS: constructor,
                 get_instances
                   RETURNING
                     value(rt_instances)   TYPE swf_utl_object_tab.
      PRIVATE SECTION.
        CLASS-DATA: mt_instances    TYPE swf_utl_object_tab.
    ENDCLASS.                    "lcl_airplane DEFINITION
    *       CLASS lcl_airplane IMPLEMENTATION
    CLASS lcl_airplane IMPLEMENTATION.
      METHOD constructor.
        APPEND me TO mt_instances.
        DESCRIBE TABLE mt_instances.
        md_counter = syst-tfill.
      ENDMETHOD.                    "constructor
      METHOD get_instances.
        rt_instances = mt_instances.
      ENDMETHOD.                    "get_instance
    ENDCLASS.                    "lcl_airplane IMPLEMENTATION
    DATA:
      gt_instances      TYPE swf_utl_object_tab,
      go_object         TYPE REF TO object,
      go_airplane       TYPE REF TO lcl_airplane.
    START-OF-SELECTION.
      " Create a few airplane instance
      DO 5 TIMES.
        CREATE OBJECT go_airplane.
      ENDDO.
      gt_instances = go_airplane->get_instances( ).
      CLEAR: go_airplane.
      LOOP AT gt_instances INTO go_object.
        go_airplane ?= go_object.
        WRITE: / 'Airplane =', go_airplane->md_counter.
      ENDLOOP.
    END-OF-SELECTION.
    Regards
      Uwe<u></u>

  • Private Constructors and Inheritance

    Hi,
    I have created a class according to the Singleton pattern, with a private constructor to prevent the public creation of class instances. Now I'd like to sub-class the Singleton, but I get errors saying the Singleton constructor is not visible. I guess this is caused by the privateness of the constructor, but I don't know if changing it to protected would ruin the Singleton pattern. Is there a good way to sub-class a Singleton?

    public class SingletonBase {
        private static SingletonBase instance;
        protected SingletonBase() throws InstantiationException {
            synchronized (SingletonBase.class) {
                if (instance != null)
                    throw new InstantiationException("single instance already exists");
                else
                    instance = this;
        public static SingletonBase getInstance() {
            return instance;
    }

  • Constructors and Private attributes

    I'm developing an object which parse a string in tokens.
    I need to override a Constructor, I need extend functionality of system constructor.
    Another issue is I need to use private attributes in my object.
    Somebody knows a way to do this?
    I appreciate some help
    Best Regards

    Daniel,
    Which release are you using? With Oracle9i R2, you can use 'user-defined constructors' (http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/appdev.920/a96594/adobjadv.htm#1009574). 'Private' attribute is not supported yet. If I know more about your usage scenario, there may be a workaround.
    Regards,
    Geoff
    I'm developing an object which parse a string in tokens.
    I need to override a Constructor, I need extend functionality of system constructor.
    Another issue is I need to use private attributes in my object.
    Somebody knows a way to do this?
    I appreciate some help
    Best Regards

  • Interface, Attribute and visibility

    Dear all,
    how can I make my attributes protected or privat in an interface. The class setting up the interface has then the getter and setter methods for the attributes (even the interface has the methods too).
    Kind regards
    Roman

    Hi Roman,
    An interface should not be pictured as a template, but more as a communication channel for different objects with common characteristics. If you want a template to create other classes, with private/protected attributes, and methods, I recommend that you use an abstract class. An abstract class will allow you to declare attributes and methods without code. Of course, you cannot instantiate an abstract class; you have to create another class that inherits from it.
    Cheers,
    Luc

  • Difference between public void, private void and public string

    Hi everyone,
    My 1st question is how do you know when to use public void, private void and public string? I am mightily cofuse with this.
    2ndly, Can anybody explain to me on following code snippet:
    Traceback B0;//the starting point  of Traceback
    // Traceback objects
    abstract class Traceback {
      int i, j;                     // absolute coordinates
    // Traceback2 objects for simple gap costs
    class Traceback2 extends Traceback {
      public Traceback2(int i, int j)
      { this.i = i; this.j = j; }
    }And using the code above is the following allowed:
    B[0] = new Traceback2(i-1, 0);
    Any replies much appreciated. Thank you.

    1)
    public and private are access modifiers,
    void and String return type declarations.
    2)
    It's called "inheritance", and "bad design" as well.
    You should read the tutorials, you know?

  • Final attributes and local variables - performance ??

    Hi all,
    I and a colleague have done some performance testing regarding the use of final attributes and final local variables, e.g.
    with final:
    public class MyClass {
      private final int i;
      public final void myMethod() {
        final int j = 5;
        // do something with i and j
    }vs. non-final:
    public class MyClass {
      private int i;
      public final void myMethod() {
        int j = 5;
        // do something with i and j
    }I couldn't find any speed differences in a small test program, but my colleague did so in his application. Who is right ??
    Still, I will have do some formal testing next week and I will post the results.
    I'd prefer the version using final anyway because I find it better readable, but the issue I am having is whether I'll spend 2-3 days going through the program making everything final or not.

    I made some tests with final arguments to a method: I could not find any difference between final and non-final arguments. code is posted below
    import java.io.*;
    import java.net.*;
    import java.rmi.*;
    import java.util.*;
    import javax.ejb.*;
    import javax.naming.*;
    import javax.rmi.PortableRemoteObject;
    import junit.framework.*;
    import junit.extensions.*;
    public final class FinalVariablesTest extends TestCase /* from junit */ {
         * Constructors
        public FinalVariablesTest(String name) {
            super(name);
         * helper methods/classes
        protected void setUp() throws Exception {
            super.setUp();
        protected void tearDown() throws Exception {
            super.tearDown();
         * Test Suite
        public static void main(String[] args) {
         junit.textui.TestRunner.run(suite());
        public static Test suite() {
            return new TestSuite(FinalVariablesTest.class);
         * Test Cases
        /** tests the effect of passing an (final or non-final) int parameter
         to a method which uses the variable in a for loop.
         <p>
         Linux System:
         cat /proc/cpuinfo
         processor       : 0
         vendor_id       : GenuineIntel
         cpu family      : 6
         model           : 8
         model name      : Pentium III (Coppermine)
         stepping        : 1
         cpu MHz         : 501.146
         cache size      : 256 KB
         fdiv_bug        : no
         hlt_bug         : no
         sep_bug         : no
         f00f_bug        : no
         coma_bug        : no
         fpu             : yes
         fpu_exception   : yes
         cpuid level     : 2
         wp              : yes
         flags           : fpu vme de pse tsc msr pae mce cx8 sep mtrr pge mca cmov pat pse36 mmx fxsr xmm
         bogomips        : 999.42
         </pre>
         <p>
         Results:
         <pre>
         java version "1.4.0"
         Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
         Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
         final     non-final
         498     500
         491     494
         491     493
         491     494
         534     494
         492     494
         491     494
         492     493
         491     494
         495     494
         4966     4944 (Totals)
         </pre>
        public final void testIntParametersToForLoop() {
         final int RUNS = 10;
         final int INNER = 1000000;
         final int OUTER = 10;
         System.out.println("-----------------------");
         System.out.println("testIntParametersToForLoop");
         for(int i=0; i<RUNS; i++) {
             outerFinalIntParametersToForLoop(INNER, OUTER);
             outerNonFinalIntParametersToForLoop(INNER, OUTER);
        private final void outerFinalIntParametersToForLoop(final int INNER,
                                       final int OUTER) {
         // with final var in for loop
         long start0 = System.currentTimeMillis();
         for(int i=0; i<OUTER; i++) {
             innerFinalIntParametersToForLoop(INNER * i);
         long end0 = System.currentTimeMillis();
         System.out.println("      final:       " +
                      ( end0 - start0 ) + " milliseconds");
        private final void outerNonFinalIntParametersToForLoop(final int INNER,
                                          final int OUTER) {
         // with non-final var in for loop
         long start1 = System.currentTimeMillis();
         for(int i=0; i<OUTER; i++) {
             innerNonFinalIntParametersToForLoop(INNER * i);
         long end1 = System.currentTimeMillis();
         System.out.println("  non final: " +
                      ( end1 - start1 ) + "       milliseconds");
        private final void innerFinalIntParametersToForLoop(final int INNER) {
         for(int i=0; i<INNER; i++) {
             int testVar = i * INNER;
        private final void innerNonFinalIntParametersToForLoop(int loops) {
         for(int i=0; i<loops; i++) {
             int testVar = i * loops;

  • First Try with JE BDB - Indexes and Inheritance troubles... (FIXED)

    Hi Mark,
    Mark wrote:
    Hi, I'm a newbie here trying some stuff on JE BDB. And now I'm having
    I am happy to help you with this, but I'll have to ask you to re-post this question to the BDB JE forum, which is...
    Sorry for the mistake. I know now that here is the place to post my doubts.
    I'm really interested in JE BDB product. I think it is fantastic!
    Regarding my first post about "Indexes and Inheritance" on JE BDB, I found out the fix for that and actually, it wasn't about "Indexes and Inheritance" but "*Inheritance and Sequence*" because I have my "@Persistent public abstract class AbstractEntity" with a "@PrimaryKey(sequence = "ID_SEQ") private Long id" property.
    This class is extended by all my business classes (@Entity Employee and @Entity Department) so that my business classes have their PrimaryKey autoincremented by the sequence.
    But, all my business classes have the same Sequence Name: "ID_SEQ" then, when I start running my JE BDB at first time, I start saving 3 new Department objects and the sequence for these department objects star with "#1" and finishes with #3.
    Then I continue saving Employee objects (here was the problem) I thought that my next Sequence number could be #4 but actually it was #101 so when I tried to save my very first Employee, I set the property "managerId=null" since this employee is the Manager, then, when I tried to save my second Employee who is working under the first one (the manager employee), I got the following exception message:
    TryingJEBDBApp DatabaseExcaption: com.sleepycat.je.ForeignConstraintException: (JE 4.0.71) Secondary persist#EntityStoreName#com.dmp.gamblit.persistence.BDB.store.eployee.Employee#*managerId*
    foreign key not allowed: it is not present in the foreign database
    persist#EntityStoreName#com.dmp.gamblit.persistence.BDB.store.eployee.Employee
    The solution:
    I fixed it modifying the managerId value from "4" to "101" and it works now!
    At this moment I'm trying to understand the Sequence mechanism and refining concerns about Cursors manipulation...
    Have you any good material about these topics, perhaps a link where I can find more detailed information on these?
    Thanks in advance Mark, thanks for your attention on this and I will post more doubts in the future for sure ;0)
    Regards,
    Diego

    Hi Diego,
    I fixed it modifying the managerId value from "4" to "101" and it works now!I'm glad you found the problem. It is usually best to get the assigned ID from the entity object after you call put(), and then use that value to fill in related fields in other entities. The primary key field (assigned from the sequence) is set by the put() method.
    At this moment I'm trying to understand the Sequence mechanism and refining concerns about Cursors manipulation...Have you any good material about these topics, perhaps a link where I can find more detailed information on these? >
    To find documentation, start at the first message in the forum, the Welcome message:
    http://forums.oracle.com/forums/ann.jspa?annID=250
    This refers to the main JE doc page, the JE FAQ and a white paper on DPL queries. The FAQ has a section on the DPL, which refers to the javadoc. The DPL javadoc has lots of info on using cursors along with indexes (see EntityIndex, PrimaryIndex, SecondaryIndex). The white paper will be useful to you if you're accustomed to using SQL.
    I don't know of any doc on sequences other than the javadoc:
    http://www.oracle.com/technology/documentation/berkeley-db/je/java/com/sleepycat/persist/model/PrimaryKey.html#sequence()
    This doc will point you to info on configuring the sequence, if that's what you're interested in.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • +, - button and inherited tick box is in disabled mode for account assignme

    In the attribute tab of org structure (PPOMA_BBP), we are not getting +, - button and inherited tick box is in disabled mode for account assignment category (attribute is KNT).
    We want to enter two values for the account assignment category with inherited tick box (ticked).
    Please suggest me how to get the +, - and inherited tick box (ticked) for the account assignment.
    Regards.

    Hi Imam,
    Unde attributes
    You will find one Application Toolbar...
    Overview, Select Attribute, Check Entries,Insert line,Delete line..
    So under All values you will find AcctAssigCat, Exculded, Default, Inheried
    Select the row and click on Insert Line, now you should be able to insert the new acct Assignment category
    rg
    sam

  • Generic and Inheritance, how to use them together?

    Hi guys, I am trynig to design some components, and they will use both Generics and Inheritance.
    Basically I have a class
    public class GModel <C>{
        protected C data;
        public C getData(){return data;}
    }//And its subclass
    public class ABCModel <C> extends GModel{
    }//On my guess, when I do
    ABCModel abcModel = new ABCModel<MyObject>();The data attribute should be from MyObject type, is it right?
    So, usign the netbeans when I do
    MyObject obj = abcModel.getData();I should not use any casting, since the generics would tell that return object from getDta would be the MyObject.
    Is this right? If yes; did someone try to do that on netbeans?
    Thanks and Regards

    public class GModel <C>{
    public class ABCModel <C> extends GModel{public class ABCModel <C> extends GModel<C>{
    ABCModel abcModel = new ABCModel<MyObject>();ABCModel<MyObject> abcModel = new ABCModel<MyObject>();

  • Private attributes are not private

    Please consider the following....
    // this is a class by someone else.
    class A{
      private Integer secretPinNumber =
        new Integer(100);
    // and I write this class
    class B extends A{
      // there is a method in here but I won't tell
      // you what it is yet.
    //When we extend something, the private attributes
    // of the extended object are hidden, right?
    // Not if you so this.....
    // Sneaky method in class B
    public Integer stealPINNumber(){
      // cast myself as my super object and since then
      // we are of the same object type, I have access
      // to all private stuff in the super object.
      return ((A)me).secretPinNumber;
    // And keep in mind that if I get the OBJECT PINNumber,
    // I can change it and the changes will show up in class A.Is this s security hole?
    If I have the spec's and code for someone elses class, can I extend it, manipulate it, and become a hacker?
    Am I stupid and everyone knows this and I am late to the party?
    Thoughts?

    The answer to my question is,
    I am stupid. I don't pay attention to the details.
    For clarification I did the following...
    class superclass{
      private Integer PIN = new Integer(100);
      // this is the part in my code that I forgot.
      protected Integer getSecretPin(){
        return PIN;
    class sub{
      sub me;
      public sub(){
        me = this;
      // Sneaky stuff
      public Integer getPIN(){
        return
          ((superclass)me).getSecretPin();
    }I was tracking down a bug and was writing some output debugging and THOUGHT that I had stumbled on a security thing. On further inspection into the superclass code I had really accessed a protected method. My compiler ignored the casting.
    Thanks to all for "Looking into it."
    Peace

  • Trying to access a private attribute of a class in the same package

    Hi,
    I have defined a private attribute in a class
    class Sample {
         private String newString = "hello";
    in another class I am trying to access newString attribute using reflection api. It is throwing hte following exception
    java.lang.NoSuchFieldException: value
         at java.lang.Class.getDeclaredField(Unknown Source)
         at refletionpack.mainclass.main(mainclass.java:20)
    any ideas how to do it exactly? Should stringclass.getDeclaredField("value")
    have the field name(newString) as a parameter?
    public class mainclass {
         static Class stringclass = Sample.class;
         static Field stringCharsField = null;
         public static void main(String args[]){
              try{
                   stringCharsField = stringclass.getDeclaredField("value");
                   stringCharsField.setAccessible(true);
                   char[] stringChars = (char[])stringCharsField.get("newString");
                   System.out.println(stringChars);
              }catch(NoSuchFieldException ex){
                   ex.printStackTrace();     
              }catch(IllegalAccessException ex){
                   ex.printStackTrace();     
    }

    Hi,
    to obtain the value of your private attribute you have to change two lines of code. At first you have to tell your class and not the field that private attributes can be accessed by using stringClass.setAccessible(true);After that you have to specify the name of the attribute to obtain which is called newString in your class which results in
    stringCharsField = stringClass.getDeclaredField("newString");For the invocation of the method get(Object) you need an object first that is an instance of the analyzed class by calling Object sample = stringClass.newInstance.
    Then you can retrieve the actual data of the requested field by calling String string = (String) stringCharsField.get(sample);A simpler solution would be when you make your attribute newString static. Then you can omit the necessary object for the retrieval of the attribute data and the line would result in String string = (String) stringCharsField.get(null);.
    For further issues considering reflection you should read the appropriate API.
    Hope it helps.

  • How to call a private attribute from a funcion module?

    Guys,
    I am trying to call a private attribute but of course it does not recognize the attribute. I am not very familiar with ABAP Objects, so i need some help on this. What is the solution as i need to get values from the fields which are inside the private attribute of the class CL_HRPA_INFOTYPE_CONTAINER. The private attribute name is a_primary_record.
    Any help will be appreciated.
    Thanks
    Nahman

    Hi Sushanth,
    We save the text not as fields in a ztable directly but as a text.Please check the format below since it is based on a working code....
    first you need to create a text in s010 transaction...
    there should be some key based on which you plan to save the text..imagine it is Purchase order then..PO+item numner is always unique.eg:0090010(900PO/item10).so in the code you can append these two and they will be unique..so you can always retrieve them,overwrite,save them anytime you need
    **************data declarations
    TYPES: BEGIN OF TY_EDITOR,
    EDIT(254) TYPE C,
    END OF TY_EDITOR.
    data: int_line type table of tline with header line.
    data: gw_thead like thead.
    data: int_table type standard table of ty_editor.
    ****************fill header..from SO10 t-code..when you save you need the unique key..youfill it here and pass it in save_text function module
    GW_THEAD-TDNAME = loc_nam. " unique key for the text -> our unique key to identify the text
    GW_THEAD-TDID = 'ST'. " Text ID from SO10
    GW_THEAD-TDSPRAS = SY-LANGU. "current language
    GW_THEAD-TDOBJECT = 'ZXXX'. "name of the text object created in SO10
    *To Read from Container and get data to int_table
    CALL METHOD EDITOR ->GET_TEXT_AS_R3TABLE
    IMPORTING
    TABLE = int_table
    EXCEPTIONS
    ERROR_DP = 1
    ERROR_CNTL_CALL_METHOD = 2
    ERROR_DP_CREATE = 3
    POTENTIAL_DATA_LOSS = 4
    others = 5.
    IF SY-SUBRC 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    loop data from int_table and save to int_line-tdline appending it.
    *save the text
    CALL FUNCTION 'SAVE_TEXT'
    EXPORTING
    HEADER = GW_THEAD
    TABLES
    LINES = InT_LINE
    EXCEPTIONS
    ID = 1
    LANGUAGE = 2
    NAME = 3
    OBJECT = 4
    OTHERS = 5.
    IF SY-SUBRC 0.
    ENDIF.
    *To pass to Container
    CALL METHOD EDITOR ->SET_TEXT
    hope that the above sample with helps you solve the problem
    Please check and revert,
    Reward if helpful
    Regards
    Byju

  • Private - encapsulation or inheritance (but not both)

    Suppose that your class has some internal computation or logic that it performs, and that you wish to encapsulate this in a method that can not be called by other classes.
    You provide public methods that filter, format, or somehow modify the input and/or output of this encapsulated method.
    class pseudoCodeClass {
    private coreLogic(Objects inputs) {
    Maybe some complicated math stuff;
    Or password stuff;
    Or pay out functionality for a slot machine;
    return(stuff);
    public getUserData(inputs) {
    format/check the inputs;
    coreLogic(inputs);
    format the output;
    Now, how do you leveradge the power of OO inheritance to extend the internal logic that you encapsulated? If you make the interal logic private, then it's encapsulated, but you lose the power of OO inheritance, or you can make it protected and lose the encapsulation. I thought an OO language was supposed to have encapsulation and inheritance, not encapsulation or inheritance. (And, yes I realize that there is some techincal sense in which private methods are still inherited, but I'm talking about the general OO concept of inheritence where it includes overriding or extending.)
    Suppose you want to:
    class pseudoCodeSubclass extends pseudoCodeClass {
    private coreLogic(inputs) {
    super.coreLogic(inputs);
    additional more specific code; // The whole point of OO inheritence
    You can't extend super.coreLogic through your access to super.getUserData because it does all sorts of filtering and formating that is not a part of the internal logic that you wish to extend/override. And, providing other more public accessor methods to the core logic just defeats the encapsulation.
    I have seen many discussions of this, but none with any answers to my satisfaction. One line of answers is that you don't want encapsulated stuff to be part of your object's contract. Some times people with this sort of answer even suggest coppying the code from the super class into the subclass. People with this sort of answer don't seem to even want the option to use inheritence because of the obligation that might go with it. But without the option of inheriting encapsulated logic, they are forced to either use cut and paste (in an OO language that seems wrong to me) or to abandon encapsulation all together. Being forced into those 2 extreems doesn't seem to me like it would simplify future support of your class, and future support seems to be the primary point of the contract line of response.
    The way some people argue about this, I amost want to say - Look! In C you can encapsulate everything you want, and never have to worry about inheritance. (But you still shouldn't have to cut and paste.)
    Another line of response that I have seen is that private methods should only be used in breaking up code that would have gone into a single method. In other words, the private methods aren't really 'units of program logic' they are just a mater of organizational convenience. So if you had:
    public oneBigMessyMethod() {
    100 lines of A;
    100 lines of B;
    100 lines of C;
    you could maintain it as:
    public oneBigMessyMethod() {
    a();
    b();
    c();
    private a() {
    100 lines of A;
    private b() {
    100 lines of B;
    private c() {
    100 lines of C;
    I agree private works well in this situation. Presumably since a(), b() and c() are divided up for convenience rather than because of distinct logical function, you wouldn't want to extend just a() with inheritance. But this also seems to dodge the question. Just because sometimes you might not want encapsulated functionality to be available for extention, does not mean that you would never want it. I think that I'd also have to disagree with the permise that encapsulation is only for hiding stuff that is just a convention of convenience. The main point of encapsulation is to hide information or functionality. If encapsulation is only used for the convenient breakdown of your primary functionality, then all of your primary functionality is public, package or protected. That does make it inheritable. But, now all of the primary functionality is a part of the contract for that class.
    Is there an answer to this issue that does not ignore the value of either encapsulation or inheritance?
    There is one way that I can see to do exactly what I think should be possible. That is to put only classes from the same hierarchy in a package. Then both package and protected effectively provide encapsulation with the ability to inherit (and you do still have the option to use private or final if there is a case where you want to disable inheritence).
    What I'd like to know is - What do people actually do? In the real world, do people:
    1) use private + cut and paste
    2) use package/protected + self discipline
    Where 2 is that you drop encapsulation within your package but then excercise self dicipline and just don't call/access stuff that you intend to be for that class only...
    Or is there some 3rd thing that I'm missing? I've tried to think how maybe you could design your objects in such a way that you'd never need to inherit/extend something that you would also want to encapsulate. But I just don't see how that's possbile.
    So, what do people do?
    Chris

    First of all, you have got to understand that I am not
    suggesting that Private and Final should be changed or
    removed from java. It looks to me like there should
    be an additional access option (and there was
    originaly).
    I understand that if a class inherits something, it
    could expand the access or put public accessor methods
    around it. Obviously with ultra sensitive code this
    would be a nightmare. So private and final are very
    important. But if the very possibility of another
    class expanding a given level of access is a reason
    for not even having that level of access, then why do
    we have package and protected?
    There are a great number of places in common coding where that access does restrict usage in a usable way.
    >
    If the only re-use of your code that you allow is
    through the public interface, what do you even need an
    OO language for? Just for the polymorphism and a
    different way to organize your code?
    Not sure what you mean by that but see below.
    But as I've said. I've seen this whole thing argued a
    number of times. But what I haven't seen is any
    explanation of what people who take the poslition that
    I'm taking actually do when they write code. Because
    I can sit here with a bunch of other people and say 'I
    wish Java had this or that'. And then of couse a
    bunch of people will resopond and say 'no that's dumb'
    or 'I don't see the point'. But at the end of the
    day, Java still is what it is. So, arguing about what
    it 'should be' is not going to effect how anyone
    codes.
    Sure it can. That is why java now has assert().
    So, what I started out wanting to know is how people
    actually code. Particularly people who wish that Java
    had a subclass only access modifier.
    I don't wish that.
    Perhapse I should also be asking about how things are
    done by people who see this level of access as
    unnececary. How they code is easy enough to
    understand. Making everything that is not intended to
    be accessed by any other class private is easy enough
    to do. But what would be interesting to know is how
    do you design your classes to leveradge inheritance if
    you do this. Maybe there is some way of desinging
    around ever having 'internal functionality' that you
    would want to extend and I'm just not getting it.
    There are three broad classifications of objects.
    1. Those that only use encapsulation
    2. Correct inheritence hierarchies
    3. Incorrect inheritence hierarchies
    The first of those, which I consider most classes to fall into, do not need this.
    The third area occurs when programmers use inheritence as a convenience mechanism to propogate behavior amoung different classes rather than using encapsulation as should be done. They don't understand the difference between "is-a" relationships (design) and coding convienence. I would estimate that at least 50% of existing object hierarchies fall into this area. Since in this case the entire design is wrong an extension is not needed.
    The second area is the only correct area where this might be needed. Since I personally believe that very few classes belong in hierarchies and this proposed extension would only be useful in a sub fraction of those. Since the correct usage is so small I don't think it would be useful addition to the language.

  • Mapping private attribute in workbench

    Hi,
    The mappingworkbench will not generate a toplink-deployment-descriptor.xml for directly mapped attributes that have accessibility private. Other comments in this forum and weblinks that date from Webgain-Toplink describe that this should be possible.
    So my questions are:
    - where can I find current toplink documentation that describes how to map private attributes?
    - how can I get around the fact that the mapping workbench does not accept methods with private accessibility?
    Thanks for your insights,
    Joost de Vries
    Nederland

    Hi Donald,
    First; what I want to do is create a 'value object' [cf. Fowler], that is: a java object that can be given values for its attributes at creation time, but not afterwards.
    So the way I try to accomplish that is by making the mutator (set-method) private.
    This is how to recreate the situation: I have a working mapping. I change the set method of an attribute to private. I restart jDeveloper (*), I generate the toplink-deployment-descriptor.xml. The generation fails with the message 'Method setDjiNummer(Integer i) has private access in class org.myOrg.MyClass'.
    Sincerely,
    Joost de Vries
    Nederland
    (*) by the way: is there a better way to make sure the Toplink Workbench sees changes made to java classes?

Maybe you are looking for