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

Similar Messages

  • 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

  • Why private variables, while still can be accessed by accessor methods

    Agreed it is well defined way of encapsualtion. But i wonder how it works differently. can any one explain . We declare a varibale as private which can be accessed by accessor (set/get) methods which are usually public. so why dont we say vairbkles itself as Private ??
    Pls explain

    Not only that, but imagine the case where you have an api method, getTotal(). Your first iteratation you have something like:
    double gross;
    double net;
    double commission;
    so to get the total you may want gross - commission = net. Thus your method may look like:
    public double getTotal()
    return gross - commission;
    But later on, iteration 2 or so, you find out you need to account for taxes, so now you don't want to break the code, the result should be the same, the NET total. However, you now need to account for taxes:
    public double getTotal()
    return (gross - commission) + tax;
    Without breaking any code and all while maintaining the actual API definition, you have made a public accessor method provide more functionality. All code using the getTotal() method wont break nor has to be recompiled and even better it now takes into account tax.
    Now, there is one "sticky" issue in the above. Because the getTotal() makes direct use of "private" variables, you may not get the "right" tax. In other words, what if there is state and local tax that need to be added? You may have two variables:
    double localTax,stateTax;
    The problem is, do you want your method like this:
    public double getTotal()
    return (gross - commission) + localTax + stateTax;
    Or would it look (and possibly account for future updates) better like so:
    return (gross - commission) + getTax();
    The thing is, what if later on you have additional tax to handle? Sure, you can simply add it to the end, adding it, what ever. But by making a "helper" method of getTax(), you might have on iteration 2:
    private double getTax()
    return localTax + stateTax;
    and in iteration three, you may have:
    private double getTax()
    return localTax + stateTax + salesTax;
    Now, unless you are calling code in an intensive performance needy loop, making a couple of helper method calls won't hurt performance at all, and it will greatly enhance your code quality because you can easily change the implementation of the method(s) used, without affecting the API.

  • 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

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

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

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

  • Accessing Private variable using reflection

    Is someone have code snippet for accessing private varaible using reflection
    Here is my code snipper
    import java.lang.reflect.Field;
    public class test1234 {
    private String t;
    public test1234() {
    public String show() {
    return t;
    import java.lang.reflect.Field;
    public class Test123 {
    public Test123() {
    public static void main(String[] args) {
    test1234 test12341 = new test1234();
    try {
    Class cls = test12341.getClass();
    Field fld = cls.getField("t");
    fld.set(test12341, "12");
    catch (Exception e) {
    System.out.println(e.getLocalizedMessage());
    I am getting exception when i try to access.
    java.lang.NoSuchFieldException
         at java.lang.Class.getField0(Native Method)
         at java.lang.Class.getField(Class.java:826)
         at Test123.main(Test123.java:24)
    Thanks in advance

    Thanks for your response. After setting accessible to true i can able to set into private variable.
    Thanks a lot.

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

  • 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

Maybe you are looking for

  • Why doesn't voice-over work in one portion?

    I'm doing my first voiceover and it seems to be fine except for one photo session of clips.  For some reason it says I'm recording and all indications are there when finished.  But when I playback, it's like the recording didn't work.  Other clips in

  • Report localization

    Hi, i'm trying to localize a report on SSRS 2012. I'm using VS 2012 Here is my solution setup. I have 2 projects one for the localization implementation that contain resx files and the class that pools the values from resex and one project for the re

  • Use Microsoft Online Directory Services as a user authentication provider for our own SharePoint farm?

    Hi, I've managed to configure my farm so that  Microsoft Online Directory Services (Office 365 etc.) can be used for STS authentication, but what I'm actually trying to do is allow user authentication - that is, I'm hoping to be able to use the user'

  • Display 'No Data Found' message w/ htmldb PopUp

    Hi all, Is it possible to control message within htmldb PopUp Lov, sort of 'No Data Found' available in Report template under topic 'When No Data Found Message'? Thx lam

  • How to replace string with image( Say Emoticons )??

    Hello Friends !! I am working on chat messenger and want some help in "How to access Emoticons when somebody typed :), ;), :)) and many more strings.....?" Is there any sample code to do that job or any function to perform such task?? Thanks in Advan