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

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.

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

  • How can I make a member of one class accessible from another class?

    I thought by making a data member protected it was available to all members of the package, but the compiler is giving me an error. If I put the class name dot the data object it thinks it is a function and gives an error.

    I can't post actual code or I'll get in trouble.
    I can't create an instance of A because the class
    needing to call the structure is a Thread and there
    will be multiple instances of it.
    I need one solid structure and it can't be static
    because it has to be ablet o change.So you can't use a static and you can't use an instance. So how exactly do you ever access A?
    BTW you are describing the impossible so you need to take a deep breath and give an explanation that makes even a modicum of sense. Hint: what you have described thus far is nonsensical enough that nobody is going to want to steal your precious code trust me.

  • Is it possible to sample a color for a gradient directly from the artwork?

    The title says it all.

    Here's an example.
    On the left is an A with a gradient fill.
    On the right is a copy of the same, expanded. (Select gradient and Object : Expand...)
    The expanded version consists of lots of little rectangles of flat colour and a A-shaped clipping mask.
    The rectangles can of course be selected individually with the direct selection tool, so you can make swatches of any of them.

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

  • LMS3.2: is it possible to modify timeout session

    Hi,
    On windows, is it possible to modify the default timeout session ?
    What is the default value ?
    Many thanks for your help,
    Elisabeth

    which timeout?? - I assume you are talking about the web server timeout !?
    I found this in one of my notes I made years ago ...
    ... the entry is still there in LMS 4.1 so I believe it is still valid...
    (I do not know if you have to restart dmgtd afterwards)
    make a backup of the following file:
        NMSROOT/MDC/tomcat/webapps/classic/WEB-INF/web.xml
    open the file in a text editor and look for the tag below; the session-timeout is given in minutes (default: 2h);
    keep in mind that changing the value has impact on the web server load (i.e. do not make it too long..)
    the tag should be at the very end of the file:
            120

  • Address Book possible to modify views in column

    Is it possible to modify the view preference in order to allow the Prefix (a title like Dr) to come after the name, so it shows as Brown, David, Dr?
    That would allow me to sort by last names and see it in an alphabetical list form which I would like.
    I currently am using Now Contact and like its flexibility, but would prefer to switch over to Apple Address Book

    That is not possible, but if you do not use the suffix as a field, maybe you could add that field - which would show after the name - and use it as the prefix field?
    hope this helps

  • 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

  • Possible to modify default module settings for large deployments?

    Is it possible to modify the default threshold and action settings for select modules, so that everything is good to go as soon as I add the node into SMC?
    I am trying to find a way to easily standardize the monitoring and notification settings across the environment.

    Hi mcomdsm,
    I think the easiest way to standardize your thresholds and actions settings would be to use the Manage Jobs feature, which allows you to create tasks like loading/unloading modules, adding rows to specific modules, setting up alarm thresholds and actions and apply it to a user-defined group of objects. This way, if you add a new node to Sun MC, you can run the same task already saved in managed jobs against the new node.
    There is a nice example on how to use Manage Jobs here: [http://forums.halcyoninc.com/showthread.php?t=97&highlight=threshold]
    Pegah Garousi
    Halcyon Monitoring Solutions

  • Est-ce qu'il est possible de modifier le site web fait avec muse depuis Adobe Business Catalyst ?

    Bonjour,
    Est-ce qu'il est possible de modifier le site web fait avec muse depuis Adobe Business Catalyst, sans avoir d'abbonnement muse ?
    Merci d'avance
    Hello,
    Is it possible to change the website made with Muse from Adobe Business Catalyst, without having abbonnement muse?
    Thank you in advance

    Claire Corteville a écrit:
    Hello
    Je sais que ce chat existe en français, mais je ne trouve plus le lien.
    Je l'ai déjà utilisé, tu discute en français,  en direct avec un vrai être humain.
    Ils sont très sympas et très efficaces
    Ca y est ! je l'ai trouvé  
    http://helpx.adobe.com/fr/contact.html?product=creative-cloud&topic=downloading-updating-a nd-installing-apps
    Tu cliques sur "j'ai encore besoin d'aide" en bas de la page.
    Il est indiqué si un agent est disponible ou non
    a++

  • Access Modifier private

    Hi
    1.
    EX Code in java:
    private class SS{  }
    There is any way i can save a file as SS.java and i need to compile this without error like - private might not allowed
    2. How to replace a String value?
    Ex String x="abc";
    Is there any way to replace this string without using any other string methods plz tell the answer.

    vijay_raga wrote:
    private class SS{  }
    There is any way i can save a file as SS.java and i need to compile this without error like - private might not allowed
    // private
    class SS {}Satisfied ? BTW ,private modifier cannot be applied to class.But I guess this would not answer your question !!!
    >
    2. How to replace a String value?
    Ex String x="abc";
    Is there any way to replace this string without using any other string methods plz tell the answer.Replace with what ?
    And what revolution do you wish to make by doing these things ?
    Thanks.

  • Getting Private Constructor of a Class

    Hello all,
    Is there any way to get the private constructor as we get the public constructors using Class.getConstructors() ?
    getConstructors() method is not returning the private constructors, but I need the info about the private constructors also....so if it is possible, please let me know...
    Thanks

    tullio0106 wrote:
    I know, however it's also impossible to invoke private methods but, using reflection, You can.That's a complete different thing. If the private method is not static, it is invoked on the current instance.
    Is it also possible to use private constructors in the same way.
    The problem I'm facing is to create a new instance of a class which extends another class and I need to use a private constructor of the superclass (I've no sources of that superclass).First, the Constructor of a class has to invoke a Constructor of a superclass as the first operation (either implicitely invoking an empty constructor or explicitely). There is no way to do any other operation before that. Second, a reflectively fetched Constructor instance always only can create instances of the class it is defined at (using newInstance()). So, yes, you could get access to a private Constructor. With that, you may be able to create a new instance of the class it is defined for. But that's about it.

  • Accessing private method of a class from report

    Hello All,
    I would have to access a private method of a class from a report.
    Is it possible to access private mehod otherthan from its own class and friend classes.
    Please guide on this. If is possible, to access please give some sample code.
    Thanks & Regards,
    Vishnu Priya

    Hi,
    By using the friend concept you can access private attribute or method in outside class.
    Try the following code,
    CLASS C1 DEFINITION DEFERRED.
    CLASS C2 DEFINITION CREATE PRIVATE FRIENDS C1 .
    PRIVATE SECTION.
    DATA : NUM TYPE I VALUE 5.
    METHODS : M2.
    ENDCLASS.
    CLASS C2 IMPLEMENTATION.
    METHOD M2.
    WRITE:/5 'I am method m2 in C2'.
    ENDMETHOD.
    ENDCLASS .
    class c1 definition.
    public section .
    methods : m1.
    endclass.
    class c1 implementation.
    method m1.
    DATA : OREF2 TYPE REF TO C2.
    CREATE OBJECT OREF2.
    WRITE:/5 OREF2->NUM.
    CALL METHOD OREF2->M2.
    ENDMETHOD.
    endclass.
    START-OF-SELECTION.
    DATA : OREF1 TYPE REF TO C1.
    CREATE OBJECT OREF1.
    CALL METHOD OREF1->M1.
    Regards,
    Jeyakumar.A
    Edited by: Jeyakumar Aasai on Apr 14, 2011 11:51 AM

  • Can I make methods which are public in a parent class into private in a child class ?

    I suspect the answer to my question is probably no, but...
    I have a parent class that provides several general purpose methods, I also have a child class which is intended to provide a more specific set of methods for manipulating the data in the class. As a result, calling some of the parent's methods on the child class can provide results that I'd rather not let the users of the child class have to worry about. It seemed (from my rather naive OOP experience) that the nicest way to do this would be to make access to some of the parent's public methods be private in the child class. This doesn't seem to be trivially possible.... ?
    Gavin Burnell
    Condensed Matter Physics Group, University of Leeds, UK
    http://www.stoner.leeds.ac.uk/

    Hi Gavin,
    Unfortuneately I don't think this can be done. You can use an overide VI to change the functionality of a method in a child class but it has to have the same scope and the method it overides.
    Regards
    Jon B
    Applications Engineer
    NI UK & Ireland

Maybe you are looking for

  • OO ALV - No Output, Please help

    hello all... in this alv.. i used the static call instead of creating a custom container. i couldn't get the output. please help. <code part too large, removed by moderator, please stay below 5000 characters, counting each single one ;)> Edited by: T

  • Look for download Adobe Acrobat 9

    Hello, I lost my installation disk Adobe Acrobat version 9 that came with the ScanSnap S1500 that I bought at the end of 2010. Where can I download Adobe Acrobat again, knowing I have my serial number for version 9? thank you Didier

  • Problem with 3g after update 7.1.2

    I do the update 7.1.2 and now my 3G don't work i need help

  • Not able to import Idoc in to XI Design Environment

    Hi all, I am facing error while importing Idoc from a SAP Retail R/3. the error is : <i> >>>Is the target system online? >>>Check the connection data (note that server names and groups are case-sensitive) >>>Tips for administrators (see the configura

  • Charm implemenation for transports in solman 7.1

    Hi Guru's, Can anyone help me to get knowledge in charm implementation for transports in solman. I am new to solman , can anyone help here. Help is much appreicated. Thanks, Pradeep.