About private variables

Is there any way of accessing Private variables of a class into another class?

The whole point of "private" is to make the variables private to the class. Your only sensible option is to use the "bean" standard, with setXXX() and getXXX() or isXXX(). For example:
public class ABC {
    private boolean myLogic = false;
    private String myString = null;
    public boolean isMyLogic() {
        return myLogic;
    public void setMyLogic(boolean newMyLogic) {
        myLogic = newMyLogic;
    public String getMyString() {
        return myString;
    public void setMyString(String newMyString) {
        myString = newMyString;
}Or, if side-effects are not a problem, just make the variables public.
You may find the following links useful.
http://java.sun.com/docs/books/tutorial/javabeans/index.html
http://java.sun.com/products/javabeans/docs/spec.html
Good luck!

Similar Messages

  • 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

  • Private variable issues

    Hello,
    While studying I have come up with this problem a few times and was wondering if you could help me.
    I am currently working with linked list examples and the variables used have default package access. I am however told that the variables should normally be declared private.
    So I made a kinda dummy class which shows my problem.
    public class Private
         private Private unreachable;
         private String greating="hello";
         public Private()
              unreachable = null;
              greating="";
         public String getGreating()
              return greating;
         public Private getReach()
              return unreachable;
    public class PrivateWork
         private String differentGreating;
         private Private reachMe;
         public PrivateWork()
              differentGreating="";
              reachMe=null;
         public void changeGreating(String change)
              Private p = new Private();
              p.greating = change;     //produces "greating has private access in the class Private" error
              p.getGreating() = change; //produces "unexpected type" error
              reachMe = p;
    public class TestPrivate
         public static void main(String[]args)
              PrivateWork p = new PrivateWork();
              p.changeGreating("Good Morning");
    }I know that by making the Private class an inner class of PrivateWork I can keep the variables declared private and the "p.greating = change;" will work.
    However is there another way I can access the "greating" variable from the changeGreating(String change) method in the PrivateWork class.

    I am currently working with linked list examples and the variables
    used have default package access.What variables are you referring to?
    p.greating = change;     //produces "greating has private access in the class Private" error That one should be pretty obvious because it is the definition of private: you can't use objects of the class to access private variables.
    By the way, "greating" is spelled greeting.
    p.getGreating() = change; //produces "unexpected type" errorI'm not sure about that one. But, you can split that statement up into two lines and you won't get a compile error:
    String gr = p.getGreating();
    gr = change;However, I don't think that is going to do what you expect. Try to predict the output of this example:
    class Private
         private String greeting="hello";
         public String getGreeting()
              return greeting;
    public class AATest1
         public static void main(String[]args)
              Private p = new Private();
              String gr = p.getGreeting();
              gr = "Goodbye";
              System.out.println(p.getGreeting()); //Output??
    }

  • Are private variables of VO/AM/...also passivated?

    Hi,
    In my JClient application in order to avoid the transaction becomming "dirty" when setting transient attributes => display field, I did the following:
    Transient attribute: AttrTransient
    Added a private variable Number attrTransient
    public Number getAttrTransient()
    // return (Number)getAttributeInternal(ATTRTRANSIENT);
    // here I call my calculation method
    return this.attrTransient;
    public void setAttrTransient(Number value)
    // setAttributeInternal(ATTRTRANSIENT, value);
    this.attrTransient = value;
    In my JClient environment it works ok.
    Question:
    In a STRUTS-ADF where the connection management is different, will my variable attrTransient be part of the passivation mechanism?
    In other words will the user get the value of attrTransient when using the same ViewObject instance?
    If yes, is this also true for added variables to application modules or Entities?
    Thanks
    Fred

    Hi guys,
    Thanks for your help. I really was drowning in a glass of water. Although now I am looking forward to learn and understand all about passivation, the issue was not related with that.
    The logic implemented checks certain characteristics for the logged in user. With this particular user the logic applied was different in term that, programatically, there was being applied a ViewCriteria. After researching and consulting I realized that when a VC is applied programatically , all the others view criteria (already applied for that VO in the AM) are lost. Hence, no matter that I was executing with all the params, at the end, the querybuilder would just bind the variables for the VC assigned to the VO. In my case, just the one I've applied programatically.
    Regards

  • Extending Private Variables

    Can someone explain to me how to extend a private variable. I think I am looking at it all wrong.
    This is what I'm thinking:
    public abstract class SuperClass{
    private int x = 2;
    private int y = 3;
    public class SubClass extends SuperClass{
    public int addTest{return x + y;}
    I think the addTest should compile and return 5. (Instead it doesn't compile). I realize that a private variable cannot be accessed outside of its own class. But SubClass is extending the SuperClass variables. So shouldn't x and y be private to SubClass now? Otherwise, it seems like I have to redeclare x and y. This would be losing the benefits of the object oriented write once theory.
    Any help is greatly appreciated.
    Thanks,
    Chris

    One correction above: public int addTest(){return x +
    y;}.
    The class still won't compile though (getting the
    message: x has private access in SuperClass).
    My questions above remain the same.
    Sorry about that.Subclasses do not inherit the private members of the superclass. If you want to expose the superclass's members to only the subclass the member must be declared as protected. Here's a link to Sun's Java tutorial that explains what a subclass can inherit from the superclass:
    http://java.sun.com/docs/books/tutorial/java/javaOO/subclass.html

  • Enforce setting private variable in subclass with abstract method

    Hi,
    Is this something that is common usage/practice?:
    public abstract class Base {
        private int importantPrivateVariable = setImportantPrivateVariable();
        protected abstract int setImportantPrivateVariable();
    }I would like to enforce the extender of the class to set a private variable, but as there is no abstract variable in java, I can only use a method for it.
    Thanks,
    lemonboston
    Edit: the variable could be protected as well, I suppose this is not important here, but correct me if I am wrong

    lemonboston wrote:
    Hi,
    Is this something that is common usage/practice?:I don't think that's so common, but that's code easily understandable. However there are several problems with this approach:
    public abstract class Base {
    private int importantPrivateVariable = setImportantPrivateVariable();
    protected abstract int setImportantPrivateVariable();
    }I would like to enforce the extender of the class to set a private variableThat's no what your code implements: your base class forces the subclasses to return an int value, and the Base class uses that value to assign it to the variable.
    Therefore the method should be called get<Something> (e.g. <TT>getInitialValueOfImportantVariable()</TT>+ to have a naming consistent with its signature (it returns a value, whereas a regular setter method should declare a void return type: <TT>protected abstract void setImportantPrivateVariable(int someValue);</TT>).
    Edit: the variable could be protected as well, I suppose this is not important here,Well, yes, this is "important" - at least, there a noticeable difference: the variable being private, the base class is free to handle it as it sees fit (e.g., assign the value at construction time and never modify it afterwards). If the variable was protected, the subclass could modify in ways and at times not known by the base class.
    but correct me if I am wrongThere's a trap in this construct: the method is called in the variable initializer, that is, behind the scenes, approximately during the execution of the Base class constructor, so before the subclass constructor. So, you are calling a method on an object that is not fully initialized (e.g. some of its attributes may still be <TT>null</TT> at this stage). There is a rule that discourages such situations, that goes something like "don't call non-private and non-final methods from a constructor".
    To avoid this trap, two options:
    - require an int argument in the Base class's constructor , as was suggested above
    - don't get and set the value of the important variable in the initializer or constructor code, but from a special method in the base class instead:
    public abstract class Base {
        private int importantPrivateVariable; // default value is zero
    // or alternatively:
    //    private int importantPrivateVariable = ...; // Some default value
        protected abstract int getImportantPrivateVariable();
        public void initializeImportantPrivateVariable() {
            importantPrivateVariable = getImportantPrivateVariable();
    }That construct is a degenerate form of a common design pattern known under the name of Template Method (where a base class method calls generally several subclass methods in a specified order and with a specified chaining, leaving it to the subclass to implement the details of the methods).
    The drawback is that the client code (the one that uses the Base instance) has to know when to call that initialization method, whereas the constructor-based initialization lets the client code free to not care at all.
    Much luck,
    J.

  • Tables where I can find information about IP variables, Infoprovider aggreg

    Hello All,
    Tables where I can find information about IP variables, Infoprovider aggregation level and filter.
    The tables where we have info about tthe user exit variables. Similar to that of UPC* tables in BPS.
    Thanks a lot,
    Karthik Krishna

    RSRPARAMETRIZA for Bex Analyzer 7.0
    RSRVARIANTDIR     for Bex Analyzer 3.x
    RSRVARIANTDIR     Directory of Variants for Queries and Selection Objects               
    RSRVARIANT             Variant Values BEX               
    We can access to value of one variant with name of query COMPUID (from RSRT --> Technical Informatione -->Data from Query Definition  --> Techn. Definition Name) or with the name of Variant from RSRVARIANTDIR (the same for the technican nema of query COMPUID)
    Edited by: Pierfrancesco Marvulli on Aug 31, 2011 3:23 PM

  • [svn] 3438: Forgot to change a private variable to protected in my previous check-in.

    Revision: 3438
    Author: [email protected]
    Date: 2008-10-01 08:27:31 -0700 (Wed, 01 Oct 2008)
    Log Message:
    Forgot to change a private variable to protected in my previous check-in.
    Modified Paths:
    blazeds/trunk/modules/core/src/flex/messaging/services/messaging/ThrottleManager.java

    Hi Ignacio ,
    To change the username you should follow these steps ;
    1-You should have to use nQUDMULGen command to export your rpd into a file.Go to ...OracleBI\server\Bin
    ex. nQUDMULGen -u Administrator -p Administrator -r C:\OracleBI\server\repository\paint.rpd -o c:\paint.txt
    2-After importing try to find your user and change its settings.
    3-Then import it back to your rpd.
    ex. nQUDMLExec -u Administrator -p Administrator -i c:\paint.txt -b C:\OracleBI\server\repository\paint.rpd -o C:\OracleBI\server\repository\paint2.rpd
    The new rpd is going to be created (paint2).Test the new rpd.If its OK.Then replace with your original rpd.
    I hope this method works...

  • Can one obj access a private variable of another obj of the same class

    Can one object access a private variable of another object of the same class?
    If so, how?

    Declaring variable private means you can not access this variable outside class
    But other objects of same class can access it. Because each object have separate copy of variable and may have diff. contents for same variable.

  • Multithread & private variables ?

    Hi,
    I would like to know if we can have private variables when we have multiple threads from the same class : in fact even if i declare a variable private when it is changed it is for all threads together, and for the future thread too : how can this be done please ???

    Hi !
    I'm sorry but really it doesn't work : i'm calling this servlet many times using get and st is everywhere set to carine...then I'm calling the post method that set up st to canard in all threads...but if i call a get again then st is set to carine again and everywhere : that means it is not private variables for each threads, I'm sorry but really I would like to know to do that properly....what's wrong ????
    Thank you for your help
    package servlettest;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class carine
        extends HttpServlet {
      private static class ThreadState {
        public String owner;
      private static ThreadLocal state = new ThreadLocal() {
        protected Object initialValue() {
          return new ThreadState();
      ThreadState st;
      public void init() throws ServletException {
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws
          ServletException, IOException {
        st = (ThreadState) state.get();
        st.owner = "carine";
        synchronized (this) {
          while (true) {
            System.out.println("st contains : " +  st.owner);
            try {
              this.wait(2000);
            catch (InterruptedException ex) {
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws
          ServletException, IOException {
        System.out.println(st.owner);
        st.owner = "canard";
    }

  • Accessing private variables

    I'm a little confused. I know that using private instance variables is good practice, and that the appropriate way to access those variables is with accesser methods (getXXX(), etc.). Since the variables are private, you can't access them by just referring to "testClass.variable", right?
    Well, I was reading up on the Comparable interface today, and found a code example where a class implemented a compareTo() method like this:
    public int compareTo(Object o) {
       if (privateVariable < (TestClass) o.privateVariable) {
          return -1;
       } else {
          return 1;
    }But privateVariable is declared as a private variable. So why is it that you can refer to o.privateVariable in the compareTo() method? Is it just because o is cast as a TestClass object, and the compareTo() method is inside of the TestClass class? Even if that's the case, it still seems weird to me; if privateVariable is declared private, I'd think that any reference to a TestClass.privateVariable variable would throw an exception, even if the reference is within the TestClass. This just seems different to me than referring to the privateVariable variable within TestClass, because that obviously refers to the member of the current instance, not a different instance.
    Anyway, any explanation would be appreciated.
    Rich

    Yes, 'private' means 'private to this class', not 'private to this object'.
    In this way, it behaves somewhat like a 'friend' variable. The basic idea of making variables private is to hide the implementation behind a class, which still holds even with the compareTo method (you can't use it to figure out that there's a variable called 'privateVariable', when using it from outside your class.)

  • Question about Local Variables (Multiple answers welcomed!)

    A couple of questions about Local Variables
    1. Programmers always say: “Do not abuse of Local Variables”. I’d like to know, when and where Local variable are most efficiently used?
    2. If I have to create a couple of local variables, is there anyway to “clone” them without going through the repetitive “create/local variables” mouse click each time? (When I try to copy and paste, it creates a new variables instead of the one that I am trying to reproduce)
    3. Which is faster in execution: Updating a variable through a) writing to property node/value or b) through local variable
    Everyone’s input is welcomed, so if this question is already answered, please
    feel free to add additional comments/answers!

    1. Use Local Variables in user interface code and no where else. The only exception is using a local variable of a cluster output to define the datatype for a bundle by name node.
    2. You can drag copy them then right click to get to a menu of all the currently defined controls and indicators on the VI.
    3. B. The problem with A is that it forces a thread switch to the user interface thread--which can take time if you aren't already in it, and it's a very convoluted process under the hood. NI's advice never update indicator values through a property node unless you absolutely, positively can't figure out some other way of doing it.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Storage of Private Variables...

    I know u all are right but the thing here is that ... when we instantiate a sub class memory for every inherited member is allocated(including private) to its object in heap.
    I just want to know that why private members are inherited if they are simply inaccessible by the sub class......are they inherited just to waste memory........

    The thing that u are saying is very much correctbut
    the point is that the private variable name used
    within the base class but why it comes to the sub
    class........and then it is invisible to it...Read this agani (posted by warneja):
    A subclass instance is still an instance of thebase class too
    (the same object, not another one).It sounds like you don't understand what he is trying
    to say. There aren't two objects in memory. I.e it's
    not one object for the base class, and another for
    the subclass. There is only one object in memory, and
    that object has all fields and methods from both
    classes.
    Kaj(All in that post was directed at the OP, even though it looks like I'm talking to warneja)

  • Subclass Private Variables

    This is such a basic question I decided to post it here.
    Does a subclass get its superclass's private variables?

    So, a subclass cannot changeyes it can but not directly
    cannot accessyes it can but not directly

  • Encapsulation hide private variable

    As below code showing that you cannot directly access the private variable as i understood, Pls guide.
    public class EncapsulationDemo{
       private int ssn;
       private String empName;
       private int empAge;
       //Getter and Setter methods
       public int getEmpSSN(){
       return ssn;
       public String getEmpName(){
       return empName;
       public int getEmpAge(){
       return empAge;
       public void setEmpAge(int newValue){
      empAge = newValue;
       public void setEmpName(String newValue){
      empName = newValue;
       public void setEmpSSN(int newValue){
      ssn = newValue;
    public class EncapsTest{
       public static void main(String args[]){
       EncapsulationDemo obj = new EncapsulationDemo();
      obj.setEmpName("Mario");
      obj.setEmpAge(32);
      obj.setEmpSSN(112233);
       System.out.println("Employee Name: " + obj.getEmpName());
       System.out.println("Employee SSN: " + obj.getEmpSSN());
       System.out.println("Employee Age: " + obj.getEmpAge());

    As below code showing that you cannot directly access the private variable as i understood,
    That code shows NO such thing.
    Tell us what line you think you are 'directly' acessing a private variable. Looks like you are using accessors for ALL accesses to me.
    See The Java Tutorials trail 'What Is an Object'. It discusses encapsulation.
    What Is an Object? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Co…
    Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

Maybe you are looking for

  • DW CS3 loses CDATA directive

    DW 9.0 Build 3481 on Windows XP. I'm converting the results of a mySQL query into XML, so that I can use Spry. I paraphrased an example on the Spry web site to do this conversion and it works great. However, I noticed that if I made changes to the pa

  • MM - Purchase Requisition Conversion

    Hi everyone, When I'm creating a Purchase Requisition, the systems gives a valuation price. When I'm converting the same Purchase Requisition to Purchase Order, the systems tells me that "Net Price must be greater than 0". I would like the Purchase O

  • InDesign CS5 won't export to PDF

    I've been having a problem recently when exporting to PDF in InDesign CS5.  I get an error message which says: 1 problem was found with a background task: Export: "NameOfDocument" (1) It won't export to PDF.  What can I do about this?  Many thanks.

  • Problem on Deactivation of a User exit

    Hi all, SAP Gurus, I would like to seek for your help regarding an error I encounter upon transporting the deactivation of a user exit to Q00. We activated a user exit EXIT_SAPLMLSR_001 (user exit of ML81N) and transported the changes up to Productio

  • Create a FS quotation in CRM to replicate to BaS

    Dear Experts:          We are using SAP CRM to create a FS saving account quotation. We also want the quotation to replicated to BaS to create a banking contract.  I accessed CRM WebUI with FS manager to create a quotation with "a saving account prod