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.

Similar Messages

  • Warning: Variable in inherited class hides private variable in base class?

    Hello,
    I've come across a simple case like this:
    class A {
      private:
        int varA;
    class B : public A {
      B() {
        int varA = 5;       // does it hide A::varA ?!
    };which is causing my Studio 11/12 compiler front ends to issue a warning like:
    "..., line 8: Warning: varA hides A::varA."
    when I try to compile with default settings.
    I'm aware that this warning can be easily worked around, but I'm still wondering what the standard says about this?
    Does B::varA really hide A::varA even though it is declared private?!
    Looks like a small bug to me.
    Can someone please try my example with the latest and greatest Studio compiler?
    Thanks,
    Jochen
    Compiler details:
    # /usr/sunstudio12.1/bin/version
    Machine hardware: i86pc
    OS version: 5.10
    Processor type: i386
    Hardware: i86pc
    The following components are installed on your system:
    Sun Studio 12 update 1
    Sun Studio 12 update 1 C Compiler
    Sun Studio 12 update 1 C++ Compiler
    Sun Studio 12 update 1 Tools.h++ 7.1
    Sun Studio 12 update 1 C++ Standard 64-bit Class Library
    Sun Studio 12 update 1 Garbage Collector
    Sun Studio 12 update 1 Debugging Tools (including dbx)
    Sun Studio 12 update 1 IDE
    Sun Studio 12 update 1 Performance Analyzer (including collect, ...)
    Sun Studio 12 update 1 Performance Library
    Sun Studio 12 update 1 Scalapack
    Sun Studio 12 update 1 LockLint
    Sun Studio 12 update 1 Building Software (including dmake)
    Sun Studio 12 update 1 Documentation Set
    version of "/usr/sunstudio12.1/bin/../prod/bin/../../bin/cc": Sun C 5.10 SunOS_i386 Patch 142363-03 2009/12/03
    version of "/usr/sunstudio12.1/bin/../prod/bin/../../bin/CC": Sun C++ 5.10 SunOS_i386 128229-04 2009/11/25
    version of "/usr/sunstudio12.1/bin/../prod/bin/../../bin/dbx": Sun DBX Debugger 7.7 SunOS_i386 2009/06/03
    version of "/usr/sunstudio12.1/bin/../prod/bin/../../bin/analyzer": Sun Analyzer 7.7 SunOS_i386 2009/06/03
    version of "/usr/sunstudio12.1/bin/../prod/bin/../../bin/dmake": Sun Distributed Make 7.9 SunOS_i386 2009/06/03

    jroemmler wrote:
    Steve_Clamage wrote:
    Accessibility versus visibility is part of the standard. [...]Ok, If that's the case, then the warning is caused by design and not by Studio C++.Yes, sort of.
    >
    I assume that other compilers do not complain because they do not strictly adhere to the standard and perform additional accessibility checks before complaining about a name clash...No. Hiding a name is legal, and your code example has well-defined behavior. There is no issue that a compiler is required to complain about. (That is, no language rule is violated.)
    If name hiding results in an invalid program, the error is due to the effects of hiding the name, not the hiding itself. Having a warning about the name hiding would help you find the reason for the error in that case.
    The C++ standard requires a "diagnostic message" for most violations of rules. Compilers generally treat these violations as fatal errors. The standard does not require or forbid any other kind of diagnostic message. That leaves compiler implementers free to emit, or omit, any warnings they think will best serve their customers.
    Compilers vary in what sorts of warnings (non-fatal observations) they emit. Most compilers, including Studio C++, provide ways to control the kinds of warnings you see. Compilers that don't warn by default about name hiding might provide a warning if you ask for it. For example, Studio C++ offers these options to control warnings:
    -w Do not emit any warnings
    +w Emit additional warnings
    +w2 Emit still more warnings about picky portability issues
    -errtags Emit a tag with warnings for use with -erroff and -errwarn
    -erroff=... Do not issue the listed warnings
    -errwarn=... Treat the listed warnings as errors
    -xwe Treat all warnings as errors
    You can read more about these options in the C++ Users Guide.

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

  • Private Variables

    What is the use in declaring a variable as private . Because if the user has to modify the variable we have to provide the user with get and set methods .
    He will declare an Object of that class and calls set /get methods. Instead we could have declared that variable as public and allow him to change directly?Is it something to do with "DataHiding" . If so how?

    What is the use in declaring a variable as private .
    Because if the user has to modify the variable we
    have to provide the user with get and set methods .Users don't modify variables. Code does. Often times good design dictates that no code outside the declaring class should be able to directly access a variable. So we make it private. Google for encapsulation or data hiding.
    He will declare an Object of that class and calls set
    /get methods. Instead we could have declared that
    variable as public and allow him to change
    directly?Is it something to do with "DataHiding" . If
    so how?Googlel for "why get and set are evil" or something like that. The author claims that get and set methods are no better than simply making the variables public. His comments are a bit extreme, but there's some truth to what he says.
    If you just blindly add get/set for every variable, then, yes, there's no point in making them private. However, you can do things with public methods on private variables that you can't do with public variables--change the underlying implementation, do validation of set values, compute values on the fly for get values. Get/set don't always have to simply be this.x = x or return x.

  • 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

  • How to hide some variables on variables screen in web report (in WAD)

    I need to hide some optional variables (not all of them) on variables screen in web template.
    Hiding the whole selection screen is not an option, since users have to populate other variables and some variables are mandatory.
    Web template is based on a query that can be run in BEx Analyzer by superusers - and there they need all variables. I want to use the same query both in BEx Analyzer for superusers and on the Portal for regular users. For portal version though I need to hide some of the variables on the selection screen. Is it possible at all?
    I would like to avoid creating two separate queries - one for Analyzer and one for Portal.

    if the variables are optional and mandatory both avaialble
    then there is no chance that u can hide them
    the only option is to create a save as QUERY and remove those variable.
    it is not possible to just hide the variable screen...
    if u hv used they will be displayed....
    if u dont want it dont use it...
    and if really using another query is not advisable as u said
    the only thing i can say is that... try to interact with ur security person
    ask him u need to create several authorization objects for several variables
    if that is possible
    let him create those
    assign those specific authorization object to specific user id
    use it for specific variables u need
    tat way super users with specaial authorization can acess the same query and can see specific variables
    regular users withouts authorization of variables can see rest of variables.

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

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

  • How to hide Text Variable in the Query title

    Hi guys,
    here again in a very easy pratical issue.
    I need to insert a text variable in a report title.
    The variable is updated with an exit and the text is get once the query is executed. This works fine.
    My problem is that in report selection (so opening the query and between queries available for an Infoprovider) I see the tech variable name of the query. Do you know if there is a method to hide the variable or if it is possible to valorize it when the report title in the report selection is displayed?
    Thanks in advance
    Bye!

    Hi, thanks for your answer.
    Also SAP marks this as a limitation.
    Bye!

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

  • 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

  • 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";
    }

  • 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

Maybe you are looking for