Public vs. private attributes

Hello,
I have a class with several attributes one of which points to an object of another class (i.e. private Account account;). Is there any really horrible reason I can't set this to be a public attribute? I ask this because I'm running a web app that sends class attributes, one of which is that "account" object, and to get an attribute from that "Account" class it has to be set to public. If i don't have it as public then i'll have to run a query in my database using account information which seems like a waste of processing time if i already have the object. I appreciate your help.
Thanks!

Rather than making the attributes public, keep them private, and, if you must expose them, do so via public get/set methods. This allows you to do things like validation, caching, etc., and allows you to change how others read and write those attributes without changing client code, just the code in the get set methods. It also conforms to Javabeans standards, and may make those classes easier to use, control, or monitor in certain frameworks.
Having said all that, it's generally considered better OO not to expose attributes directly in most cases. Sometimes it's the right thing to do, but often times, you only need to expose behavior--a method where another class can tell this object what to do, and it can figure out how to do it using its attributes.

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>

  • What is the difference between Public and Protected Attributes

    hi ppl,
             what is the difference if i declare attributes under public or protected to access the private method.for both (public or private) section iam getting the same result.
    CLASS CL DEFINITION.
    *protected section.
      public section.
    DATA: M TYPE I VALUE 100.
    private SECTION.
    METHODS: FREE.
    ENDCLASS.
      CLASS CL IMPLEMENTATION.
       METHOD: FREE.
         WRITE:/ M.
         ENDMETHOD.
      ENDCLASS.
    CLASS CL1 DEFINITION INHERITING FROM CL.
    public section.
    METHODS: FREE1.
    ENDCLASS.
      CLASS CL1 IMPLEMENTATION.
         METHOD: FREE1.
         WRITE:/ M.
         ENDMETHOD.
      ENDCLASS.
    DATA: OBJ  TYPE REF TO CL1.
      START-OF-SELECTION.
      CREATE OBJECT : OBJ.
      END-OF-SELECTION.
      CALL METHOD: OBJ->FREE1.
    Please use meaningful subject in future questions and Post in correct forum*
    Please learn to use  tags around your ABAP
    Edited by: Vijay Babu Dudla on Dec 1, 2008 12:37 AM
    Edited by: Matt on Dec 1, 2008 4:16 PM

    hi,
        Iam really soory people..It wont repeat again.pls guide me in this regard
    hi ppl,
    what is the difference if i declare attributes under public or protected to access the private method.for both (public or private) section iam getting the same result.
    CLASS CL DEFINITION.
    *protected section.
    public section.
    DATA: M TYPE I VALUE 100.
    private SECTION.
    METHODS: FREE.
    ENDCLASS.
    CLASS CL IMPLEMENTATION.
    METHOD: FREE.
    WRITE:/ M.
    ENDMETHOD.
    ENDCLASS.
    CLASS CL1 DEFINITION INHERITING FROM CL.
    public section.
    METHODS: FREE1.
    ENDCLASS.
    CLASS CL1 IMPLEMENTATION.
    METHOD: FREE1.
    WRITE:/ M.
    ENDMETHOD.
    ENDCLASS.
    DATA: OBJ TYPE REF TO CL1.
    START-OF-SELECTION.
    CREATE OBJECT : OBJ.
    END-OF-SELECTION.
    CALL METHOD: OBJ->FREE1.
    Edited by: Matt on Dec 1, 2008 4:18 PM

  • 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.

  • Public Read-Only Attributes

    I'm trying to pick up ABAP on my own by reading through various resources I've collected and writing my own programs.  Unfortunately I don't have an experienced ABAP guru to ask questions of.  I'm hoping someone can help me with the following:
    Based on my other programming experience I know that it is very common for object attributes to be defined as private and then accessor/mutator (getter/setter) methods to be defined to provide access to the attribute.
    In my study I noted that ABAP allows attributes to be made public but declared to be read-only.  This would seem to permit a structure where accessor/getter methods are not needed (the attribute can be read externally) and one would only have to define a mutator/setter method.
    My question:  what is typically done in 'real-world' programs?  Is there any reason why using read-only would be more or less preferred?
    Thanks for any help that can be provided.

    Hello Tony
    Below I have listed a few examples from standard ABAP classes. I cannot say whether you find more public read-only attributes than GETTER methods - you will find examples for both of them.
    I could imagine that before it was possible to use the functional method call in ABAP that public read-only attributes were an alternative to the "verbose" method cal (see below)l.
    " RE-FX: Contract
    CL_RECN_CONTRACT-IF_RECN_CONTRACT~MS_DETAIL   " public read-only attribute
    " MM: Material
    CL_IBASE_R3_MATERIAL->GET_MARA  " GETTER method
    "FI/CO: Company Code
    CL_REEXC_COMPANY_CODE=>GET_DETAIL  " GETTER method
    " HR: Employee
    CL_PT_EMPLOYEE->IF_PT_EMPLOYEE~PERNR   " public read-only attribute
    " Assumption: CL_IBASE_R3_MATERIAL would have
    " a public read-only attribute MS_DETAIL (of TYPE mara)
    " Normal method call (verbose):
    CALL METHOD go_material->GET_MARA
      RECEIVING
        R_MARA = ls_mara.
    " Functional method call:
      ls_mara = go_material->get_mara( ).
    " Accessing public attribute
      ls_mara = go_material->ms_detail.
    Regards
       Uwe

  • 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.
    %

  • Private attributes & class property definition errors

    I'm setting up functions in a document class file, then from there I am going to call that function from a movieclip in flash.  For some reason, maybe I have things set up wrong, but it is throwing me errors such as below:
    Line 37 1013: The private attribute may be used only on class property definitions.
    What am I doing wrong here and is there something I am not understanding?
    Here is my .as code.
    modal.as >
    package {
         import flash.display.*;
         import flash.events.Event;
         import flash.events.MouseEvent;
         import flash.display.*;
         import flash.events.*;
         import flash.net.URLRequest;
         public class modal extends MovieClip {
              public function modal() {
         private var currentlyShowing:MovieClip=null;
              public function showModalContent(clip:MovieClip):void {
                   if (currentlyShowing!=null) {
                        removeChild(currentlyShowing);
                   currentlyShowing=clip;
                   addChild(currentlyShowing);
              public function removeModalContent():void {
                   if (currentlyShowing!=null) {
                        removeChild(currentlyShowing);
                        currentlyShowing=null;
    And here is my code that is on the timeline:
    slideshowimages_mc.one_mc.addEventListener(MouseEvent.CLICK, oneClick);
    function oneClick(event:MouseEvent):void {
         var bigimagebg_mc=new mc_bigimagebg  ;
         showModalContent(bigimagebg_mc);
         bigimagebg_mc.x=200;
         bigimagebg_mc.y=170;

    unnest all the named functions and that variable:
    package {
        import flash.display.*;
        import flash.events.Event;
        import flash.events.MouseEvent;
        import flash.display.*;
        import flash.events.*;
        import flash.net.URLRequest;
        public class modal extends MovieClip {
            private var currentlyShowing:MovieClip=null;
            public function modal() {
            public function showModalContent(clip:MovieClip):void {
                if (currentlyShowing!=null) {
                    removeChild(currentlyShowing);
                currentlyShowing=clip;
                addChild(currentlyShowing);
            public function removeModalContent():void {
                if (currentlyShowing!=null) {
                    removeChild(currentlyShowing);
                    currentlyShowing=null;

  • 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?

  • Viewing document characteristics in Easy DMS public and private folders

    We have classified our documents in SAP Document Management System.  We are viewing the DIRs in Easy DMS.  In the public and private folders, the classification characteristics columns can be added to the screen report, however the values for the characteristics do not appear in the columns.  If we use the search function and view those same documents in the search screen, the characteristic values do appear.  How can we get these values to appear in the public and private folder views?  There does not seem to be an OSS notes which address this discrepancy.  In advance, any assistance is most appreciated.

    Hi Barry - As Daniel explained, sometimes system behaves if the Default box is not checked but I want you to check the EasyDMS version/patch you are using. Below is the screenshot of latest version/patch.
    If you have old verison/patch, please implement the latest version/patch and check.
    /Tilak

  • How to know whether a function is public or private in PL/SQL?

    Hi friends,
    I want to know if there is any method to specify a function or procedure as public or private?
    If so how?

    Hmm.
    Public or private?
    Ok. Probably two explanation ->
    1. If you have the execution/select/modify privileges the that function or procedure is public else private. Else according to those available features you can call it private(If you have no privs to your schema) or partial private(Never heard this word in Oracle - just to make you understand. ;) If you have one or few privs missing from your list of privs).
    2. If you create any procedure or function inside package specification - then it can called public provided that you should have proper privs as discussed in point 1. If your procedure or function declared inside the package body then it is private. You cannot directly call them outside that package. If any other method of that package is calling it - then only you can use it.
    Regards.
    Satyaki De.
    Edited by: Satyaki_De on Nov 17, 2008 12:21 AM

  • BizTalkServer 2010 SFTP Adapter from CodePlex - Configuring send and receive locations with SSH public and private keys

    Hi there,
    I am looking for step by step instrcutions on how to configure SFTP Codeplex adapter for both receive and send ports.
    Out business partner with whom we push/poll the files from wants us to use SSH encryption/decryption etc.
    Just wondering if the following functionality is supported in Codeplex SFTP adatper without having to write any code.
    Appreciate if there is manaul to do this for SFTP. BTW I do have all the our public and private keys and business partners Public key for configuring.
    For Send port: 1. we would need to encrypt the file with our business partners public key
                          2. sign the file with our private key.
                          3. Send the file through to SSH client which eventually transfers to Remote server.
    Receive port:   1. Connect to SSH Server with SSH-2 key and receive the file
                          2. Verify the file's digital signature agaisnt the Business partners PGP public key
                          3. Decrypt the file using our PGP Public key
    Thanks in advance

    Yes it is supported.
    You can find its documentation in this link 
    You can find section X.509 Certificate Identity Keys
    You can set public and private key in property SSH Identity thumbprint  of send and receive port
    I prefer to test it using client tool like
    FileZilla or WinSCP then test it using sftp adapter
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer

  • Public vs Private

    When I publish my app through the folio creator tools I'm given the option of Public or Private. Can someone explain what exactly they mean? If I set it to Private can I still share it with clients? Do they have to sign into their Content Viewer Apps with my login or can they still use their own? What about Public? Who can see it then?
    I presume these decisions have no bearing when I eventually send the app to iTunes, or do they?

    OK so if I'm creating a new folio for my Multi-folio app, all I do is publish it as Public and people who have downloaded my App (Custom Viewer) will have the option of downloading it? Does this mean that folios created for multi-folio apps are published without going through iTunes' approval process and will just appear immediately after they've been published through the Folio Creator Tools?
    With regards to publishing Private, do readers have to login with my account details to view or will can I share it as I would an app hosted on Acrobat (ie. to anyone with an Acrobat account)?

  • SQL Installation for SharePoint 2013 - Windows Firewall - Profile - domain, Public and Private - Which ones to choose?

    Hi there,
    I am setting up SQL Server (to be used in our SharePoint 2013 farm).
    The Firewall exception for SQL server gives me three choices in Profile section as 
    Domain, Public and Private profiles 
    Which ones should I choose please? 
    Thank you so much.

    Hi,
    According to your description, my understanding is that you want to set the firewall exception for SQL server.
    Domain profile—This profile is active when the server is connected to an Active Directory (AD) domain via an internal network. This is the profile that's typically active, because most servers are members of an AD domain.
    Private profile—This profile is active when the server is a member of a workgroup. Microsoft recommends more restrictive firewall settings for this profile than for the domain profile.
    Public profile—This profile is active when the server is connected to an AD domain via a public network. Microsoft recommends the most restrictive settings for this profile.
    More information, please refer to the link:
    http://windowsitpro.com/windows/windows-server-2008-r2-firewall-security
    Please 'propose as answer'
    if it helped you, also 'vote helpful' if you like this reply.
    Prabhu

  • 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

Maybe you are looking for

  • IMac error message with 32Gb compact flash card from Nikon D4

    Hi I have a iMac 2.8Gig core 2 duo running 10.7.4 - I get a error message (the disk inserted is not readable by this computer) when using 32gb compact flash cards from my Nikon D4, have tried bith Sandisk and Lexar cards same error message. However b

  • Connecting to Airport Express via Linksys Wireless-G adapter

    I am trying to use a linksys compact adapter (WUSB600N) to connect a Windows XP PC to my Airport Express- The linksys monitor CAN detect the Airport Express, but "cannot associate with the access point" for a few seconds, then "can associate... but c

  • Automati-payment

    in automatic payment programme we can use the house banks:- as like this:- SBI                   ICICI                   HSBC                   CITI BANK  MY REQUIREMENT IS THE I HAVE ONLY PAYMENT FOR THE HSBC is it possible or not if possible how (g

  • Problem with creating app

    I am trying to make a simple picture sliding game like this and I am not sure the best way to go about it. I am not sure if I should simply display the image and then cut it into six squares and put them as objects in an array. Then randomize the arr

  • Recognize COGS in intercompany billing process

    Dear expert, I read the intercompany billing process and have some confuse. The process like that: CC1(company code 1) sells to end customer, CC2 (conpany code 2) (internal relationship) issues good. 1, CC1 sells to end customer. CC1 create the SO 2,