Public methods/fields

What would be wrong with making all my fields, classes, methods, ect public. How would people be able to tamper from outside with them.

Another reason to make variables private is to separate the interface of your class from the internal implementation. A simple example of this is a class to represent a complex number (a + bi). You would have some public methods for manipulating the complex number, but you would want the actual representation of the complex number to be internal and private. Why? Because at some later time, you might want to change the internal representation, for performance reasons, or to exploit some new feature, etc.
If you had all public variables and public methods, there would be nothing you could change without requiring the users of your class to rewrite their code, which, after all, depended on all the public variables you had in it.
If, on the other hand, you had the internal representation hidden with private variables and methods, the change in implementation would be no problem and users could use your new improved class without rewriting their code.
That's one of the main benefits of OOP; being able to wall off your internal implementation while keeping a viable external interface.

Similar Messages

  • Getting list of methods/ fields using JNI ( REPOST)

    Hi All,
    Since I did noy get any response , I am reposting this....
    I am trying to get a list of all public methods & fields in a given class. But I am having trouble. Listing below shows the code I am using. In the example I am trying to get all the public methods of java.lang.String .
    But the code always prints out the 44 methods of java.lang.Class. . Can anyone help me out please ??
    jclass cls = env->FindClass("java/lang/String");
         if (cls == 0) {
              fprintf(stderr, "Can't find hello class\n");
              exit(1);
         else
              jclass jCls = env->GetObjectClass(cls);  // Get the java.lang.Class for String
                   // Get Method ID of getMethods()
              jmethodID midGetFields = env->GetMethodID(jCls, "getMethods","()[Ljava/lang/reflect/Method;");
              env->ExceptionDescribe();
              jobjectArray jobjArray = (jobjectArray)env->CallObjectMethod(jCls, midGetFields);
              jsize len = env->GetArrayLength(jobjArray);
              for(jsize i = 0 ; i < len ; i++)
                   jobject _strMethod = env->GetObjectArrayElement(jobjArray , i) ;
                   jclass _methodClazz = env->GetObjectClass(_strMethod) ;
                   jmethodID mid = env->GetMethodID(_methodClazz , "getName" , "()Ljava/lang/String;") ;
                   jstring _name = (jstring) env->CallObjectMethod(_strMethod , mid ) ;
                   char buf[128];
                   const char *str = env->GetStringUTFChars(_name, 0);
                   printf("\n%s", str);
                   env->ReleaseStringUTFChars(_name, str);
              }Cheers,
    KHK

    Forget my last post. It doesn't work at all (big-o-crash)!
    Try this instead. Maybe there is a way much simpler.
    The idea is to instanciate a String object, call getClass() on it, and from the returned object (a Class object) call getMethods().
        jclass cls = env->FindClass("java/lang/String");
        if (cls == 0) {
            fprintf(stderr, "Can't find hello class\n");
            exit(1);
        else {
            jobject strObj = env->AllocObject(cls);
            jmethodID midGetClass = env->GetMethodID(cls, "getClass", "()Ljava/lang/Class;");
            jobject clsObj = env->CallObjectMethod(strObj, midGetClass);
            jclass jCls = env->GetObjectClass(clsObj);
            jmethodID midGetFields = env->GetMethodID(jCls, "getMethods", "()[Ljava/lang/reflect/Method;");
            jobjectArray jobjArray = (jobjectArray)env->CallObjectMethod(clsObj, midGetFields);
            jsize len = env->GetArrayLength(jobjArray);
            jsize i;
            for (i = 0 ; i < len ; i++) {
                jobject _strMethod = env->GetObjectArrayElement(jobjArray , i) ;
                jclass _methodClazz = env->GetObjectClass(_strMethod) ;
                jmethodID mid = env->GetMethodID(_methodClazz , "getName" , "()Ljava/lang/String;") ;
                jstring _name = (jstring)env->CallObjectMethod(_strMethod , mid ) ;
                const char *str = env->GetStringUTFChars(_name, 0);
                printf("\n%s", str);
                env->ReleaseStringUTFChars(_name, str);

  • Final class: methods/fields automatically final?

    As a final class cannot be subclassed, methods/fields cannot be overwritten. But is there a performance/security difference between
    public final class A {
        public static final String S = "S";
        public final static do() {}
    }and
    public final class A {
        public static String S = "S";
        public static do() {}
    }?

    As a final class cannot be subclassed, methods/fields
    cannot be overwritten. But is there a
    performance/security difference betweenAll methods of a final class are implicitly final.
    Fields are not (you could demonstrate that very easily by altering the value of the field S in your example).

  • Error while calling a super class public method in the subclass constructor

    Hi ,
    I have code like this:
    CLASS gacl_applog DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS:
                create_new_a
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXPORTING  pfx_log_hndl TYPE balloghndl
                   EXCEPTIONS error
    ENDCLASS.
    CLASS gacl_applog IMPLEMENTATION.
      METHOD create_new_a.
        DATA: ls_log TYPE bal_s_log.
      Header aufsetzen
        MOVE pf_extnumber TO ls_log-extnumber.
        ls_log-object     = pf_obj.
        ls_log-subobject  = pf_subobj.
        ls_log-aluser     = sy-uname.
        ls_log-alprog     = sy-repid.
        ls_log-aldate     = sy-datum.
        ls_log-altime     = sy-uzeit.
        ls_log-aldate_del = ls_log-aldate + 1.
        CALL FUNCTION 'BAL_LOG_CREATE'
             EXPORTING
                  i_s_log      = ls_log
             IMPORTING
                  e_log_handle = pfx_log_hndl
             EXCEPTIONS
                  OTHERS       = 1.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID      sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH    sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    CLASS gcl_applog_temp DEFINITION INHERITING FROM gacl_applog.
      PUBLIC SECTION.
        DATA: log_hndl   TYPE balloghndl READ-ONLY
            , t_log_hndl TYPE bal_t_logh READ-ONLY
        METHODS: constructor
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXCEPTIONS error
               , msg_add      REDEFINITION
               , display      REDEFINITION
    ENDCLASS.
    CLASS gcl_applog_temp IMPLEMENTATION.
      METHOD constructor.
        CALL METHOD create_new_a
               EXPORTING  pf_obj       = pf_obj
                          pf_subobj    = pf_subobj
                          pf_extnumber = pf_extnumber
               IMPORTING  pfx_log_hndl = log_hndl.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    A public method of Super class has been called from the constructor of the sub class. we are getting the syntax error :
    ' In the constructor method, you can only access instance attributes, instance methods, or "ME" after calling the constructor of the superclass…'
    Can you please suggest how to change the code with out affecting the functioanlity.
    Thank you ,
    Lakshmi.

    Hi,
    Call that method by instance of Subclass.   OR
    SUPER-->method.
    Read very useful document
    Constructors
    Constructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the starting state of a new object or class. There are two types of constructors - instance constructors and static constructors. Constructors are methods with a predefined name. To use them, you must declare them explicitly in the class.
    The instance constructor of a class is the predefined instance method CONSTRUCTOR. You declare it in the public section as follows:
    METHODS CONSTRUCTOR
            IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL]..
            EXCEPTIONS.. <ei>.
    and implement it in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE OBJECT statement. You can pass the input parameters of the instance constructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in the CREATE OBJECT statement.
    The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. You declare it in the public section as follows:
    CLASS-METHODS CLASS_CONSTRUCTOR.
    and implement it in the implementation section like any other method. The static constructor has no parameters. The system calls the static constructor once for each class, before the class is accessed for the first time. The static constructor cannot therefore access the components of its own class.
    Pls. reward if useful....

  • Error while accessing a public method of applet from javascript.

    Hi,
    I am getting "Object doesn't support this property or method" error
    when accessing a public method of applet from javascript in IE 6 using
    document.applets[0].myMethod();
    The same is working in IE 7.
    Thanks in advance.
    Regards,
    Phanikanth

    I don't know why it happens, but this works for me in both versions:
    <applet ..... name="MyApplet">
    </applet>and in javascript use
    document.MyApplet.myMethod()

  • Error when calling a Webservice's public method in Forms10g

    Hi,
    I'm getting the following error when calling a webservice's public method, i'm using Forms10g 10.1.2.3
    java.rmi.RemoteException; nested exception is: HTTP transport error javax.xml.soap.SOAPException
    java.security.PrivilegedActionException javax.xml.soap.SOAPException
    Message send failed javax.net.ssl.SSLException SSL handshake failed X509CertChI have added the Jar containing the client proxy in both Classpaths(system variable and default.env), the jar has been made with jdk 1.4
    I also have tested the client proxy from jDeveloper and it's working there, but in Forms i'm getting this error.
    I guess my problem might be that i'm calling a webservice that is secured since the url starts with https
    what should i do to fix this ??
    Regards
    Carlos

    I understand, so i have a doubt, why the webservice works on jDeveloper ??Not just JDeveloper even soapUI and Neatbeans have a way of working without a client certificate installed.
    I do not know how they achieve it. I know that they work without a client DC.
    Cheers,
    PS: See this http://stackoverflow.com/questions/8887434/webservices-ssl-https, it offers a clue.
    The java programs run unhindered when one-way authentication is being used. These products ship with a digital certificate that is in the path of most popular CAs.
    Corollary, if the Web Server is configured for mutual authentication then you need to install and configure the client certificate in the tools.
    Edited by: Prabodh on Dec 5, 2012 8:36 PM

  • Calling Public Method in OOP.

    Hello All,
    How to call a Public method in one using the object of the other class.
    The second class doesn't inherit the first class.
    Thanx and Regards,
    SampathKumar.

    Got the solution.

  • Accessing a private variable from a public method of the same class

    can anyone please tell me how to access a private variable, declared in a private method from a public method of the same class?
    here is the code, i'm trying to get the variable int[][][] grids.
    public static int[][] generateS(boolean[][] constraints)
      private static int[][][] sudokuGrids()
        int[][][] grids; // array of arrays!
        grids = new int[][][]
        {

    Are you sure that you want to have everything static here? You're possibly throwing away all the object-oriented goodness that java has to offer.
    Anyway, it seems to me that you can't get to that variable because it is buried within a method -- think scoping rules. I think that if you want to get at that variable your program design may be under the weather and may benefit from a significant refactoring in an OOP-manner.
    If you need more specific help, then ask away, but give us more information please about what you are trying to accomplish here and how you want to do this. Good luck.
    Pete
    Edited by: petes1234 on Nov 16, 2007 7:51 PM

  • Accessing a public method from javascript in an applet!!!

    Hi!!
    I'm have an applet (named say applet.class) in an html page that has a public method like this....
    public void doShowFrame()
              Frame frame = new frame();
         frame.setVisible (true);
    What I want to do is to call that method with javascript, I've tried to do it like this...
    function show(){
    applet.doShowFrame();
    But when i press the button that launch the java scipt the browser says
    'applet' is unidentified...
    What's wrong, what can I do??

    http://www.google.com/search?q=applet+javascript+communication&sourceid=opera&num=0&ie=utf-8&oe=utf-8
    how hard was that? seriously.

  • Payment method field ZLSCH is hidden on FI doc item.When can it be visible?

    Hello,
    where can i customize which FI item is relevant for entering payment method value in tcode FB01, FB02, FB03. I supposed that every customer or vendor item should display (and insert during FI document posting) payment method field. If i double click on FI item (customer or vendor) sometimes i can see payment method field in subscreen "Additional details" but sometimes not. Is there any dependency with posting key or......  I tried to add this field in Fields groups but there is payment method field is not available there.
    Thanks, Zdenek.

    Hello Zdenek,
    Normally the payment method is never transferred from the master data.
    Not in the invoice, nor in the credit memo.
    If you go to the vendor's master data, use "F1" Help, you will see that the payment method (ZLSCH) is only taken by default for the automatic payment transactions. Thus it is not valid in transaction FB60 or MIRO.
    If you wish to fill the payment method in automatically, you could define a substitution rule.
    Please review the following notes to use fields in validations and substitutions:
    20637 Inserting Fields in Validations and Substitutions
    42615 Substitution in FI
    48121 User Exits in Validations/Substitutions
    Another important information is that for payment documents created by F110, if this document is reversed afterwards, payment method is cleared and this is standard behaviour.
    I believe that this answer your inquiry.
    Best Regards,
    Vanessa Barth.

  • Payment method field in Cutstomer invoice

    HI SAP Guru's
    Is it possible to add payment method field in the customer invoice
    in the first screen while entering Customer details we can see the bank details of the customer, is it possible to see payment method next to bank details?
    Thanks in advance
    venu

    OK
    I think I know you problem.
    You have posted some invoices, Vendor and you now want to change the payment method on them as this is missing.
    this is easy to fix.
    1/ go to FB02 for a document you want to change. Check if the payment method is greyed out. If not you should be able to manually change the value. If it is grey go to point 2
    2/ Go into config, SPRO, Go to ****, Document, Line item, Document Changes, Line items.
    Check for an entry for BSEG-ZLSCH. If there is one there, make sure the field is modifable. If it is not there, create an entry.
    After this config setting is made, go back to FB02 and the field should no longer be greyed out and you should be able to change it.
    If you have loads of fields to change, get an ABAP guy to create a program to use a file of document numbers to change the field.
    If this is useful please assign points.

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

  • Including External LVOOP Public Methods in Executable

    Hello,
    I have an application which on the top level must 'talk' to several different instruments; a LabJack UE9 (USB) , a Newport Motion Controller (USB-Serial), etc.    When I wrote the drivers for these instruments in LV, I used the LVOOP functionality and created individual Classes with public methods for each of the different devices I need to communicate with.  Sounds logical to me, anyway. 
    In my top-level application, I call the public methods (and must include local instances of the LVOOP classes) for those independant instrument-specific classes.  In the development mode, everything works peachy.   However, when I go to build the application executable (build), I get some weird behavior;
    Firstly, with the default setting in 'Additional Exclusions' in the Build Properties of 'Remove as much as possible', I get errors when the builder gets to my independent classes.  I get the message:
    "An error occurred while building the following file:
    C:\Documents and Settings\Wes Ramm\My Documents\Projects\RDT\LabJack\Class\Common Methods\Get DO Line State.vi
    The VI became broken after disconnecting type definitions. Open the Build Specification and choose a different option on the Additional Exclusions page."
    Ok, it seems that the class object is not linking, but I can get around that by selecting the second option in 'Additional Exclusions' ; 'Remove unreferenced project library members'.  BUT, when the build is done, I get a couple of subdirectories with vi's named for all the different class methods for each independent that I am calling.  There is no front panel or block diagram for the vis, so it looks like they are correctly 'included' in the build, but it seems cumbersome to include these subdirectories.
    I even tried to 'add' the independant classes to the project by 'Add Folder', but got the same behavior. 
    The classes that I made are not a part of the top level VI, and the top Leve VI is not a member of any of the classes, so this I think is the crux of the matter.  However, I am instantiating only the public methods, and the problems only pop up when I try to build the executable.
    Am I missing something?  Is there a more elegant way to do this?  Any advise / tutorials / knowledgebase articles you can point me to?
    The tree for the directory structure for my build looks like this (for reference)
    \\Application Directory\
                             Executable
                             \Config
                                      \ Class One.lvclass  (first external class that I am calling in my top-level vi)
                                          \ Method 1
                                          \ Method 2
                                          \ Method 3
                                           \ etc
                                      \ Class Two.lvclass
                                            \Method 1
                                            \Method 2
                                            \Method 3
                                            \ etc
    Thanks,
    Wes Ramm
    Wes Ramm, Cyth UK
    CLD, CPLI

    Hello Wes Ramm,
    It's better late than never! Hence I'm going to address some of the issues that you've brought up.
    1) Which version of LabVIEW are you using? LabVIEW 8.5 has fixed a lot of issues that occured between the Application Builder and LV Classes. If you were using LV 8.2, I would suggest changing to LV 8.5 or at least LV 8.2.1
    2) Apart from setting "Do not disconnect type definitions or remove unreferenced members" in the Additional Exclusions page, I would suggest also checking the box against "Enable Debugging" on the Advanced Page.
    The following forum post has discussed many of the problems that have come up when building an executable which uses LVOOP classes. Hope this helps.

  • Payment method fields?

    Where can I find the payment method fields.
    For example I want to write a func.spec. in which I want to know the payment method for a final bill. I want to know whether the customer paid by cash, check, routing/direct debit or credit card?
    Can anyone pls. advise in which table and fileds can I find these?
    Thanks
    Dan

    Just posting the answer that I researched and found.
    Table: DFKKKO........Doc.type (BLART)........................Origin(HERKF)..............Pmt.Method
                                           CR                                                 06                               Credit Card
                                            AC                                                06                               Routing/Debit etc.
                                            IP                                                  05                                In Person
                                            CH                                                25                                Check
    Hope this will be useful to anyone who needs it. Comments on the accuracy of the above welcomed. !
    Thanks
    Dan

  • ESS - Bank Details - Payment method field

    In the ESS --> Bank Details --> Payment method field , we would like to restrict the drop down values that are shown. In R/3 we (IT 0009) we have different values such as Direct deposit, Check , Cash etc.. but on the ESS we want only direct deposit to appear in the drop down value.
    How can this be achieved? We are on ERP 2005 , ESS 1.0 , EP 7.0

    The table "help_values" that is referred to in the code has an "Associated Type" of HRPAD_HELP_VALUE_DATA_TAB which has a "Line Type" of HRPAD_HELP_VALUE_DATA which looks like this:
    Component          RType       Component Typ   Data Type    Length    Decimal Pl    Short Desc
    FIELDNAME                      TYPENAME        CHAR         30        0             Name of Dictionary Type
    KEYCOLUMNNAME                  CHAR30          CHAR         30        0             30 Characters
    VALUECOLUMNNAME                CHAR30          CHAR         30        0             30 Characters
    DATA               <checked>   DATA                          0        0
    When I debug, before my code executes, <tabs> has three rows and two columns:
    1:   <blank>  Cash Payment
    2:   B        Bank Transfer
    3:   Q        Payroll Checks
    My code executes, deletes the "Cash Payment" line and then <tabs> has two rows and two columns:
    1:   B        Bank Transfer
    2:   Q        Payroll Checks
    And as I said, the dropdown on the screen in the portal still has three lines.  The first is blank and the second and third are "Bank Transfer" and "Payroll Checks" respectively.
    Just for fun (argh!), I experimented with an additional scenario in debug mode just to see what would happen.
    First, I commented out the line of code that deleted the "Cash Payment" line from <tabs> and then from within debug I manually altered the first line in <tabs> from <blank>   "Cash Payment" to "X"   "Test". 
    Result:  The portal screen now displayed 4 values in the dropdown box.  The first is still a blank line, followed by "test", "Bank Transfer" and "Payroll Checks"
    So it seems that there's code somewhere down-stream that is adding the blank line if there is no record anywhere in tabs where the first field is blank. (I actually ran a couple of other tests to definitively arrive at that conclusion)  Now I just have to find it.

Maybe you are looking for

  • Itunes install - No error messages, it just won't install

    New computer with Vista Premium (64 bit). Downloaded Itunes 9, run the install, _it tells me that install has completed successfully_ (the "install" is fast - less than 20 seconds), but _nothing has actually been installed_. No error messages. I have

  • BPS Documents not storing/saving in Production

    We are using the Document functionality in BPS layouts to create and store a Microsoft Word document associated with a particular cell.  We have set all the necessary characteristics' document attribute properties, and these have been generated in ea

  • AS2 connectivity issue

    Hi, I am facing an issue with connecting through AS2 server to PI server. Below is the scenario: We receive different types of files from customer (EDI and Non EDI). We have maintained one configuration scenario (CS) for EDI and another one for non E

  • WBS-Line item wise

    Dear Fnds, I maintained WBS Element Line item wise in Account assignment Tab in Sales order and i Copied the Milestone for Respective WBS. After saving the Sales ,If i go in Change /Display Mode...That WBS i can not able to find in Line item Wise. Re

  • Printing Playlists

    Hi I am into house music and I cannot work out how to print a playlist so that the title, artist, mix and length of tune is showing. I usually use CD Jewel case insert and I can only usually see either 1.) the title + Artist+ and half the mix or 2.)