Modifying private member returned by reference...

package C:  
class C
     private Vector vp;  
     // some code to instansiate vp
    public Vector getVP() { return vp; }
package B:
import C.*;
class B
    C c = new C();
    public modifyVP()
         Vector v =  c.getVP();
         // modify v
          //modifcations inside v are reflected inside vp here!!!!
}vp is passed by reference, but should not some check should take
place at some place for modifying references to private elements??...
thanx and please help...newbie to java...

yeah i guess u r right (my background is in C++) . Basically
my original problem was to iterate through a list of vectors
and then delete some (based on certain criteria). My project
is supporting M$ JVM which doesn't have iterators. Enumerators,
i think cant be used to delete or add to the same list you are
enumerating upon (correct me if this is wrong). So I decided
to fall back to returning vector and doing the check inside a for
loop. So returning vectors is a bad design. But is there some
better method in this situation???

Similar Messages

  • Is it possible to modify private member of a class directly from main?

    This is the code which modifies the private String stk[] indirectly from main method when sorting option is called from main method:
    import java.io.*;
    class Stack
        private String stk[];
        private int tos;
        private int size;
        Stack()
            size=5;
            stk=new String[size];
            tos=-1;
        Stack(int sz)
            size=sz;
            stk=new String[size];
            tos=-1;
        boolean push(String s)
            if(tos==size-1) return false;
            stk[++tos]=s;
            return true;
        String pop()
            if(tos<0) return "Stack Underflow";
            return stk[tos--];
        String[] display()//array type function to return an array called "stk"
            return stk;
        int returnSize()
            return tos;
    class myStack
        public static void main(String args[]) throws IOException
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            Stack S=new Stack();
            int opt=-1;
            while(opt!=6)
                System.out.println("\n\n\n");
                System.out.println("[1] - Create Stack");
                System.out.println("[2] - Push");
                System.out.println("[3] - Pop");
                System.out.println("[4] - Display");
                System.out.println("[5] - Display List In Ascending Order");
                System.out.println("[6] - Exit");
                System.out.print("Option: ");
                opt=Integer.parseInt(br.readLine());
                if(opt==1)
                    System.out.print("\n\nEnter the size of stack: ");
                    int size=Integer.parseInt(br.readLine());
                    S=new Stack(size);
                    System.out.print("\nStack Created...");
                else if(opt==2)
                    System.out.print("\n\nEnter String: ");
                    String s=br.readLine();
                    if(S.push(s))
                        System.out.print("\nSuccessfull...");
                    else
                        System.out.print("\nStack Overflow...");
                else if(opt==3)
                    System.out.print("\nItem Deleted: "+S.pop());
                else if(opt==4)
                    int sz=S.returnSize();
                    System.out.print("\n\n\nStack Contains: "+(sz+1)+" Item(s)\n");
                    String st[]=S.display();
                    while(sz>=0)
                        System.out.println(st[sz]);
                        sz--;
                else if(opt==5)
                    int s=S.returnSize();
                    String stc[]=S.display();
                    for(int i=0;i<=s;i++)
                        for(int j=i+1;j<=s;j++)
                            if(stc[j].compareTo(stc[i])<0)
                                String t=stc[i];
                                stc[i]=stc[j];
                                stc[j]=t;
                    System.out.println(stc[i]);
                else if(opt>6)
                    System.out.print("\nPress 6 To Exit....");

    Actually, since it is returning the reference value of the array, and he is changing the array elements using that reference, then he IS "changing the array".
    @OP:  When you return a reference value to an object (and, in this regard, an array IS an object), then use that reference value to change things in the object (NOT assigning a new value to the variable holding that reference value), then, of course, those items are changed, and everything using that same reference value will "see" those changes, as they ALL point to the SAME object.
    Edit:  My first answer was going under the assumption that you meant DIRECTLY changing (i.e. stk = ...) since all you provided was the "title" and a blurb of code.  Next time you should think about actually providing some information about the actual "problem".
    See http://www.javaranch.com/campfire/StoryCups.jsp (to get associated with the "terms" they use)
    then see http://www.javaranch.com/campfire/StoryPassBy.jsp for some easy to understand explanations of reference values and objects.

  • Is it possible to modify private member of a class directly from main function?

    This is the code which modifies the private String stk[] indirectly from main method when sorting option is called from main method:
    import java.io.*;
    class Stack
        private String stk[];
        private int tos;
        private int size;
        Stack()
            size=5;
            stk=new String[size];
            tos=-1;
        Stack(int sz)
            size=sz;
            stk=new String[size];
            tos=-1;
        boolean push(String s)
            if(tos==size-1) return false;
            stk[++tos]=s;
            return true;
        String pop()
            if(tos<0) return "Stack Underflow";
            return stk[tos--];
        String[] display()//array type function to return an array called "stk"
            return stk;
        int returnSize()
            return tos;
    class myStack
        public static void main(String args[]) throws IOException
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            Stack S=new Stack();
            int opt=-1;
            while(opt!=6)
                System.out.println("\n\n\n");
                System.out.println("[1] - Create Stack");
                System.out.println("[2] - Push");
                System.out.println("[3] - Pop");
                System.out.println("[4] - Display");
                System.out.println("[5] - Display List In Ascending Order");
                System.out.println("[6] - Exit");
                System.out.print("Option: ");
                opt=Integer.parseInt(br.readLine());
                if(opt==1)
                    System.out.print("\n\nEnter the size of stack: ");
                    int size=Integer.parseInt(br.readLine());
                    S=new Stack(size);
                    System.out.print("\nStack Created...");
                else if(opt==2)
                    System.out.print("\n\nEnter String: ");
                    String s=br.readLine();
                    if(S.push(s))
                        System.out.print("\nSuccessfull...");
                    else
                        System.out.print("\nStack Overflow...");
                else if(opt==3)
                    System.out.print("\nItem Deleted: "+S.pop());
                else if(opt==4)
                    int sz=S.returnSize();
                    System.out.print("\n\n\nStack Contains: "+(sz+1)+" Item(s)\n");
                    String st[]=S.display();
                    while(sz>=0)
                        System.out.println(st[sz]);
                        sz--;
                else if(opt==5)
                    int s=S.returnSize();
                    String stc[]=S.display();
                    for(int i=0;i<=s;i++)
                        for(int j=i+1;j<=s;j++)
                            if(stc[j].compareTo(stc[i])<0)
                                String t=stc[i];
                                stc[i]=stc[j];
                                stc[j]=t;
                    System.out.println(stc[i]);
                else if(opt>6)
                    System.out.print("\nPress 6 To Exit....");

    Short answer is: no.
    Long answer is: you should not try to. Information hiding is the fundamental principle of OOP. This means that the code dealing with an object has no knowledge about the objects inner structure. It only knows the methods provided by its interface.
    You should declare all object properties private and prevent any other code outside the owning class to manipulate it. This includes leaking properties via "getter" methods. In your example the display() method is bad in two ways:
    its name does not convey its purpose.
    it a "getter" that returns the private property stk to the caller who may change it. Eg. the caller could add or delete an entry without changing tos accordingly.
    bye
    TPD

  • Return by Reference/Return by Value

    Okay. I am suppose to create this accessor method that is not suppose to return by reference so as to protect the private variables.
    Firstly, I suppose for primitive data type I can :
    public int rtnInt() {
    int i = 0;
    int j;
    int j = i;//Primitive type creates new memory for variable
    return j; }
    Right? Or can I just return i? Will returning i result as a reference to i?
    Secondly, I am stumped on reference data type, example if I have :
    public String rtnstr() {
    String a = "a"
    String b;
    String b = a; //Can't do this right, it will just reference to the location of a?
    return b;
    So how do you actually copy a new a to and assign it to b? Oh ya, am I right to say arraycopy copies a new array and I don't have to worry about referencing?

    Noobie1987 wrote:
    Eh? So you mean to say I can just return or pass any variables, reference or primitive type, without fear of the original being modified?"Returning variables" does not pertain here, since when you return from a method, the variables are popped from from the stack and cease to exist. When you pass a variable to a method, a copy of that variable's value is used within the method. Changing the variable within the method does not affect the variable outside the method. Ever.
    But I thought 2 variables referencing the same memory location will affect each other if a change is made. AKA...
    String[] str = {0};
    String[] abc = str;
    abc[0] = 1;
    So str[0] will become 1?First, that example won't compile. Second, there is no passing of anything; just variable assignment.
    It is important to understand that variables do not contain objects. Read this: [http://www.javaranch.com/campfire/StoryPassBy.jsp]
    ~

  • Duplicate class, modifier private not allowed

    I can't get javadoc to create doc for any class I make, I keep on getting these errors
    here is the class:/**
    * Like Integer, but isn't.
    * @author Phillip Bradbury
    public class Int
      /** the internal value */
      private int i;
       * Creates an Int.
      public Int(int val)
        i = val;
       * Gets the value passed in the constructor.
       * @returns the value
      public int get()
        return i;
    }and the error:cspc49-c3018900: javadoc temppack -d doc
    Loading source files for package temppack...
    Constructing Javadoc information...
    /nfs/student1/csse/c3018900/./temppack/Int.java:5: duplicate class: Int
    public class Int
           ^
    /nfs/student1/csse/c3018900/./temppack/Int.java:8: modifier private not allowed here
      private int i;
                  ^
    javadoc: warning - No source files for package temppack
    Standard Doclet version 1.4.1
    Generating doc/constant-values.html...
    javadoc: No public or protected classes found to document.
    1 errors
    3 warningswhat am I missing?
    I've tried using -classpath and -sourcepath with a lot of different weird and wonderful paths (including ., temppack/ and somewhere completely unrelated to Java), i've tried it with a compiled .class file there and not there, i've tried remaning the class and package to random gibberish in case there was a conflict, and now I'm out of ideas.
    Thanks in advance,
    =====
    Phlip

    This is curious.
    classes
    +-doc
    +-temppack
    doc is empty, and temppack contains only Int.java
    ...but if I run
    javadoc temppack -d doc
    in the classes folder I get the duplicate class / private
    not allowed errorsIf you're using 1.4.1, it has a bug that you might be seeing
    that is present in 1.4.0 and 1.4.1 but in no other versions.
    I recommend you upgrade to 1.4.2, which fixes this bug:
    Execution: Fixed so duplicate classes are documented (4673477, tool, REGRESSION)
    http://developer.java.sun.com/developer/bugParade/bugs/4673477.html
    Here is the list of other enhancements in 1.4.2:
    http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.2.html
    execute the following on the commandline
    javadoc -package temppack
    Yep, it works perfectly with -package there!The -package option should make a difference only if
    your class or members are package-private (which they are not).
    The default is to allow public and protected program elements
    to be documented. When you add -package, all it does is
    also package-private program elements to be documented:
    http://java.sun.com/j2se/1.4.2/docs/tooldocs/solaris/javadoc.html#package
    -Doug

  • Returning remote reference

    Hi everybody, I'm having quite some trouble with RMI, everytime I try to return a reference to a Remote object on my server I get the usual "unmarshalling return" error. Problem is that my Object I'm trying to return actually implements the Remote interface:
    public interface Bank extends Remote {
         public Account create_account (String name) throws BankException, RemoteException;
    };the Implementation looks like this:
    public class BankImpl implements Bank {
         public Account create_account (String name) throws BankException {
              Account k = new AccountImpl(name);
              return k;
    }Again the interface and Implementation:
    public interface Account extends Remote {
        public Account(String name);
    public class AccountImpl implements Account, Remote  {
         private String name = null;
         AccountImpl(String name){
              this.name = name;
    };I'm quite stuck here, is there something I'm missing??? I thought that function whose return type is some implementation of the Remote interface will automatically get passed by reference with an automatically generated stub.

    It seems to me that having to actually extend the UnicastRemoteObject is quite a limitation.You don't have to. I gave you that as the simplest solution. If you don't extend UnicastRemoteObject, you have to export the object yourself with UnicastRemoteObject.exportObject(). Use the overload where you specify a port number, even if it's only zero (= any).
    And somehow I'm unable to cast the generated Proxies to my Interfaces.
    Actually I can only let my extend the "Remote" interface in my interfaces and them implement my Account interface and extend "UnicastRemoteObject" in the implementations and still it won't work.What happens? You'll have to show us the code ... btw is there something missing back there?
    Still think I'm missing something...For sure. RMI works.

  • Inclusive Free Goods Return with Reference

    Hi Gurus!
    Could you help me with my question below
    We are tring to create a sales order return with reference to a billing document. This billing document has two items where one is a standard item and the other is a inclusive free goods item.
    Example:
    1            AAA

    Hi
    When you have creating the sales order  with reference to billing document the items will be copied into the return order without any changes
    You can check the controls in the copy control VTAF
    Regards
    Damu

  • ORDERS05 - Create a Return with reference to a Sales Order

    Hi all,
    I'm trying to create a return with reference to a sales order via IDOC ORDERS05. I'm indicating referenced Sales Order number into segment E1EDK02; indicating qualifier (QUALFR = 002) and Sales order number (BELNR). By this way, I create a Customer Return but without reference.
    Which fields or segment have to be filled in order to create it correctly?
    Thanks
    Marí

    Correct...
    You need something like:
    *Get the pricing cond number.
    select single knumv from vbak into cond
      where vbeln = '0000080347'.
    if sy-subrc = 0.
    Get the pricing record which are by line item.
      select * from konv into table konv_tbl where knumv = cond.
    Loop thru them one line at a time.
      loop at konv_tbl.
       bapi_cond-itm_number = '000010'.
        bapi_cond-cond_st_no = konv_tbl-stunr.
        bapi_cond-cond_count = konv_tbl-zaehk.
    CALL FUNCTION 'BAPI_CUSTOMERRETURN_CREATE'
      EXPORTING
        RETURN_HEADER_IN               = bapi_hdr
       BUSINESS_OBJECT               = 'BUS2102'
        CONVERT                        = 'X'
      IMPORTING
        SALESDOCUMENT                 = bapi_salesdoc
       RETURN                        = BAPI_RET
      TABLES
        RETURN                        = bapi_ret_tbl
        RETURN_ITEMS_IN                = bapi_itm
        RETURN_ITEMS_INX               = bapi_itm_out
        RETURN_PARTNERS                = bapi_prtnr
        RETURN_SCHEDULES_IN            = bapi_schd_lin
        RETURN_CONDITIONS_IN           = bapi_cond.  "pricing
      ORDER_TEXT                    = bapi_text.

  • Java returning the reference of the current class.

    Hi,
    I want to write a method in Java to return the reference of the current class in a static manner i.e, without instantiating the class. Please help as to how to go about it.
    Thanks.

    Come on, at least point out where the guy is wrong.
    user563329 wrote:
    I want to write a method in Java to return the reference of the current class in a static manner i.e, without instantiating the class.There is no concept of a "current class" but I guess you meant "the class where the code is defined that the current thread is running now".
    However, that means that class (code) has been instantiated so your question makes no sense.
    If you want the class of the "current running code" use Object#getClass().
    You can reference a class without instantiating it but it will still be loaded. For example:
    public class TestInit {
        public static void main(String[] args) {
            System.out.println(Init.class.getSimpleName());
    class Init {
        static { System.out.println("Init init"); }
    // running it with java -verbose:class show Init is loaded but the static initializer is not run
    // loading lots of class ending with
    [Loaded TestInit from file:/C:/Projects/Dump2/Output/]
    [Loaded java.lang.Void from shared objects file]
    [Loaded Init from file:/C:/Projects/Dump2/Output/]
    Init
    [Loaded java.lang.Shutdown from shared objects file]
    [Loaded java.lang.Shutdown$Lock from shared objects file]

  • How to have a member formula to reference a text data type member?

    Hi there
    I am just wondering how do you use a member formula to grab the text in a text data type member?
    Our situation is that we have a text data type member in the Accounts dimension (called Project Manager). This is a free text field users can input a project manager's name. However, for our reporting purposes we want to report the Project Manager next to a list of Accounts (i.e. in the same row). The way we have tried to achieve this is to create dynamic calc text data type members in the Version dimension that simply refer to the Project Manager account using the reference function (->).
    Although this works, when we run a report we get a number (assuming this is just the reference ID to the RDBMS field) instead of the actual name. We have set the dynamic calc member to text data type as well. We are using a planning connection as well.
    Does anyone know how to make this work?
    Thanks

    Are you talking about FR reports, does it display the text if you reference the original member using a planning connection, if it does then it probably looks like you can't do it using the method you are trying as it is an essbase formula and in theory it will just return a number.
    Cheers
    John
    http://john-goodwin.blogspot.com

  • LVOOP Parent private data returned when child instance created from constant

    I have created one Parent class, and one Child class.  For each of these classes, I have created a member VI that is a constructor, whose purpose will be to initialize some constants for each class, and return the class instance.  I also have a member accessor VI for each class that returns the private data of the class (in this case a single string for each class).
    The Parent class's private data "String" is set to"Parent text" as the default value.
    The Child class's private data "Child String" is set to"Child Text" as the default value.
    The Parent class constructor works just fine.  For testing purposes, I return the text from directly unbundling in the constructor VI, and as returned from the accessor VI. The Parent constructor starts from a class constant.
    However, in the case of the Child class constructor, if I start from a class constant, directly unbundling the private data (using an Unbundle By Name function, and choosing "Child String" as the element), I get the Parent's private data!
    If I use the Child class's member VI to retrieve the text, I get the Child's private data.
    If I change the constructor to start from a class Control instead of a class Constant, I get the Child's private data.
    This only occurs  before the Child class has existed as a
    Control/Indicator. i.e. If I unbundle the private data after the class 
    is returned by any member VI, I get the correct Child private data.  So obviously something changes once the class "data" has been a control at some point.
    I am using Labview 8.6.1, Windows XP
    I have attached a small project that illustrates the problem I am encountering, without actually doing any initialization, just reading.
    Is this the intended behaviour?  Why does it matter if I start with a class constant instead of a class control?  When you drag from the Project window to the Block diagram, you always get a constant.
    Solved!
    Go to Solution.
    Attachments:
    ParentChildClass.zip ‏54 KB

    Although I was able to replicate your issue in LabVIEW 8.6.1, it appeared to run correctly in 2009.  I could not find a CAR ID but at this point can only assume that the behavior was not intended but is fixed in 2009.
    Let me know if you need me to find any further details.
    Alex Person
    NI-RIO Product Support Engineer
    National Instruments

  • I don't understand the design of inner class private member

    This is a question about the java language specification of inner classes.
    In the java langage specification document, we read
    If the member or constructor is declared private,
    then access is permitted if and only if it occurs
    within the body of the top level class (�7.6)
    that encloses the declaration of the member.
    This allows following code :
      public class PrivateTest {
        public PrivateTest()
          Hello hello = new Hello();
          System.out.println(hello.secret);
        class Hello
           private String secret = "This is a secret";
      } wherein accessing the private secret field is allowed
    from into the PrivateTest enclosing class.
    My questions are :
    a) It seems that private methods or constructors of
    inner classes have no meaning, we could also declare
    them as public. True or false ?
    b) Is there any reason that Java bypass this private
    mechanism ?
    c) Why is the above definition not written with
    "first enclosing" instead of "top level" ?
    Thanks in advance

    Private methods and constructors of an inner class can only be accessed within the outer class. Other classes can't instantiate it or use the private methods.
    You can also make your inner class private, so it is not possible to refer to the class from outside (and thereby another way of preventing it from being instantiated).
    So it does matter which access modifiers you use.
    I think top level is more precise than first enclosing, because you can have inner classes in inner classes, which are still available for the top level class (haven't tested this).

  • Enclosing class calling private constructor of private member class

    Hi all,
    I have this question concerning member classes and privtae constructors.
    public class MyTest {
        private class Inner {
            private Inner() {
                System.out.println("Why Am I here!??");
        public MyTest() {
            Inner a = new Inner();
        public static void main(String[] s) {
            MyTest z = new MyTest();
    }It doesn't work for my JDK SE 1.3.3, build 1.3.1-b24.
    It works for many other versions.
    Can somebody kindly enlighten me, should this code work?
    I really didn't think that it should, but it did!

    I am sorry. It was actually my jikes 1.15 that was causing the problem.
    After some research, I found out that my problem arose out of my understanding of OO concepts, or rather, the meaning of access modifiers in Java.
    I had thought that nobody can access a private variable/method of class except the class itself. Apparently, this is not so. The access modifiers apply to the class themselves and not the object. Thus explaining why an object can access the private variables/methods of another object of the same class.
    Actually, it's not really the case here. The Java language specs states that the inner class has total access to the enclosing class, but I could not find any word on enclosing class access to inner classes in the specs.
    As for Jikes, I really hope they will fix it soon. I like it a lot as it is significantly faster than javac for everything I have done so far.
    cheers!

  • Goods return without reference to a Material Document or delivery note

    Hi
    Is there a way to do Goods return without a material document. Please suggest.
    The situation is that a material will go to the field (material is being maintained against a serial number profile) and let suppose that it is returned after a few years of use. Then in such a situation I need to take it back into the stock through a return delivery. But it may not be possible to track the material documnet against which GI was done few years back. SO i need to have a provision that either goods be returned with a reference of a material Document OR I should be able to track the material document in the system (through a report) using the serial number. Request you to please suggest on these two cases.
    Also we are not having procurement process in our organization. we do GR and GI only in regard to inventory movement.
    Thanks,

    Check
    Customer returns without billing reference

  • Create sales order (return) with reference - PO number not copied

    Hello all,
    I have a question regarding creating a sales order (return, VA01) with the option "create with reference" where a sales order number can be added as reference.
    The system will copy values from the sales order into the return document like the item, the sold-to-party etc.
    The PO Number (customer PO number) is not being copied in our system, so I was wondering if there is a way to tell the system to copy the PO number from the sales order?
    Thanks,
    Anne

    Hi,
    In the transaction code VTAA, select the target and source document types (return order <- sales order) and click on the details button. Check the data transfer routine (the first one for VBAK) assigned here. You may need to clone this routine (in transaction VOFM -> Data transfers -> orders) and create a new routine to add field VBAK-BSTNK into it.
    Check with an ABAP'er for further details.
    Regards,

Maybe you are looking for