Accessing private field of Derived object in Base class

Hi,
I have this piece of code I wrote a while ago to test something. The issue is accessing a private field of Base class in Base but of a Derived object.
Here is the code:
class Base
     private int x;
     public int getX()
          return x;
     public int getX(Derived d)
          // return d.x;
          return ((Base) d).x;
}The commented code does not work but casting d to Base does.
Can someone please explain the reasoning for this.
Forgot to mention that the compilation error is that x has private access in Base.
Thank you.
Edited by: 953012 on Apr 1, 2013 8:42 AM

>
As I understand the explanation says that you can access any private member within the code of the class that encloses the private member. So in this case x is the private member and the line of code (return d.x) is in Base which encloses the private member. Does it have to do with the fact that the Derived class does not in fact inherit the private members of Base?
>
It has to do with the entire quote from the spec
>
A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses
>
Your code is
public int getX(Derived d)
          // return d.x;
          return ((Base) d).x;
     }The 'Derived' class is NOT 'the top level class that encloses the declaration of the member'. It does NOT inherit 'x' which is a private member of 'Base'. As far as the 'Derived' class is concerned 'x' does not exist.
>
If outside Base code I have Derived d = new Derived() and I call d.getX() then isn't that like calling d.x in myX()?
>
How is that the same? 'Base' owns 'x' and can do whatever it wants with it. 'Derived' has no knowledge of 'x' and CAN NOT access it.

Similar Messages

  • Accessing private fields from an subclass whoes parent is abstract.

    I seem not to be able to access some private fields from a subclass who's parent is abstract...
    here is some code to demonstrate this: (based on yawmark's code)
    import java.lang.reflect.*;
    import java.net.URLClassLoader;
    import java.io.*;
    import java.net.*;
    class PrivateReflection {
        public static void main(String[] args) throws Exception {
            Private p = new Private();
            File f=new File("test.jar");
            URL[] urls=new URL[1];
            urls[0]=f.toURL();
            URLClassLoader loader=new URLClassLoader(urls);
            Class c=loader.getClass();
    //        Class c=p.getClass();
            Field field = c.getField("packages");
            field.setAccessible(true);
            System.out.println(field.get(p));
    class Private {
        private String packages = "Can't get to me!";
        private void privateMethod() {
            System.out.println("The password is swordfish");
    }There is no need for a test.jar file to be created.
    I know for a fact that the ClassLoader abstract class defines a field called "packages" which is an HashMap.
    How do i access this private field?
    I am in the process of making a utility which re-compresses a inputed JAR using other compression methods than normal zip compression while still keeping the same functionality as the inputed JAR.
    I do have it working for Executable JARS: www.geocities.com/budgetanime/bJAR.html
    This old version only works for executable JARs and uses Bzip2 compression.
    I believe i have been able to solve all but one last problem to making re-compressed JARs which work as "library" JARs. This last problem is "removing" temporary prototype classes from the system loader and replacing them with the actual decompressed classes. As there seems not to be an nice way to do this i will have to manually remove references of the classes from the system class loader which is why i am asking this question.

    lol! i have solved my problem... it was because i was using the getField() method instead of the getDeclaredField() method.

  • Exchange of field info between Objects of same class

    Hi, I am a beginner in Java and this question might seem trivial.....I just wanted to know if there is a way to exchange field information between 2 objects of same class.
    Any help/comment regarding this is appreciated.
    Thanks,
    Pradeep

    You need to be more specific. If the field is public then you can access it like so:
    int a = someObject.someField;Otherwise, you need to make a method that returns that value.

  • To access a method frm a class derived frm a base class with the same name

    Here' s an example:-
    class TestA {
    public void start() {
    System.out.println("TestA");
    class TestB extends TestA {
    public void start() {
    System.out.println("TestB");
    }In main method I do this:-
    TestA testA = new TestA();
    TestB testB = new TestB();
    ((TestA)testB).start();Output :-
    TestB.
    Now when i define the method as static :-
    class TestA {
    public static void start() {
    System.out.println("TestA");
    class TestB extends TestA {
    public static void start() {
    System.out.println("TestB");
    }Then output is :-
    TestA.
    Can anyone let me know that when i say ((TestA)testB).start(); i.e i am type casting TestB obect to it base call then TestA should be printed but it doesn't print but when i declare method as static is does print TestA.
    Thanks,
    Heena

    >
    >
    Secondly, when i say ((TestA).testB).start(); output is TestB. But when i define start() method as static output is TestA. I need clarity for the same.In the static case, all that the compiler is interested in is the class of the expression before the ".". Because you've put in an explicit cast the type of expression is assumed to be TestA the compiler doesn't know what kind of object will actually be referenced at runtime. In the static case which method is called is determined at compile time.
    In the instance method case what determines the method called is determined the class of the actual, run time, value of the expression, and despite your cast, the actual value is still a reference to a TestB instance, so the TestB method is called. In the instance case which method called is determined at run time.

  • Base Class NI View Fails

    Hi
    I am currently trying to leverage of my existing codebase by creating a Base class View containing common functionality. My goal is to create the Base class in the form of a (MFC) CFormView with an associated dialog resource containing all my NI controls and underlying code. From there I intend to derive further View Classes based on the former. I have tried this and cannot seem to get the Base class to recognise its members,i.e the Ni controls, whilst the view displays fine and I can see all the Ni controls on form derived from the Base class I cannot execute any of the base class meber functions that need a reference to the Ni controls. If you could give me an example of a project that derives it view from a Base class with ActiveX contro
    ls in it I would be very appreciative.....
    Regards

    I was going to investigate it a little before posting, but
    I'm not sure I can go any further on my own.
    I am using the Yahoo Astra Flash Components. When I add a
    Tree component, and give it a dataProvider that does not use any
    nested nodes, it gives me the error. If I use even 1 nested node,
    then it works correctly.
    I am assuming that the error is stemming from the Yahoo
    Component somewhere, just need to run down what is causing it.

  • Set fields of derived class in base class constructor via reflection?

    Does the Java Language Specification explicitly allow setting of fields of a derived class from within the base class' constructor via reflection? The following test case runs green, but I would really like to know if this Java code is compatible among different VM implementations.
    Many thanks for your feedback!
    Norman
    public class DerivedClassReflectionWorksInBaseClassConstructorTest extends TestCase {
    abstract static class A {
        A() {
            try {
                getClass().getDeclaredField("x").setInt(this, 42);
            } catch (Exception e) {
                throw new RuntimeException(e);
    static class B extends A {
        int x;
        B() {
        B(int x) {
            this.x = x;
    public void testThatItWorks() {
        assertEquals(42, new B().x);
        assertEquals(99, new B(99).x);
    }

    why not just put a method in the superclass that the subclasses can call to initialize the subclass member variable?In derived classes (which are plug-ins), clients can use a field annotation which provides some parameter metadata such as validators and the default value. The framework must set the default value of fields, before the class' initializer or constructors are called. If the framework would do this after derived class' initializer or constructors are called, they would be overwritten:
    Framework:
    public abstract class Operator {
        public abstract void initialize();
    }Plug-In:
    public class SomeOperator extends Operator {
        @Parameter(defaultValue="42", interval="[0,100)")
        double threshold;
        @Parameter(defaultValue="C", valueSet="A,B,C")
        String mode;
        public void setThreshold(double threshold) {this.threshold = threshold;}
        public void setMode(String mode) {this.mode = mode;}
        // called by the framework after default values have been set
        public void initialize() {
    }On the other hand, the default values and other metadata are also used to create GUIs and XML I/O for the derived operator class, without having it instantiated. So we cannot use the initial instance field values for that, because we don't have an instance.

  • Why cannnot derived class pointer point to a base class object?

    Hi,
    Pleaseeee... explain me why cannot the derived class pointer point to a base class object.
    I know that Base class pointer can point to a derived class object.
    Thanks & Regards,
    Vig....

    Example:
    class Base
    { public: void foo(); } * pBase;
    class Derived : public Base
    { public: void bar(); } * pDerived;
    Now, what would happen if you assign pDerived = new Base() and then call pDerived->bar()?By forbidding such an assignment, compiler prevents you from writing error-prone code.

  • Casting base class object to derived class object

    interface myinterface
         void fun1();
    class Base implements myinterface
         public void fun1()
    class Derived extends Base
    public class File1
         public myinterface fun()
              return (myinterface) new Base();
         public static void main(String args[])
              File1 obj = new File1();
              Derived dobj = (Derived)obj.fun();
    Giving the exception ClassCastException......
    Can't we convert from base class object to derived class.
    Can any one help me please...
    Thnaks in Advance
    Bharath kumar.

    When posting code, please use tags
    The object returned by File1.fun() is of type Base. You cannot cast an object to something it isn't - in this case, Base isn't Dervied. If you added some member variables to Derived, and the compiler allowed your cast from Base to Derived to succeed, where would these member variables come from?
    Also, you don't need the cast to myinterface in File1.fun()
    Also, normal Java coding conventions recommend naming classes and interfaces (in this case, myinterface) with leading capital letters, and camel-case caps throughout (e.g. MyInterface)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can a derived class catch base class object

    can a derived class object catch a base class object
    e-g if i have a class
    class Test {
    // code
    }and
    class Test2 extends Test {
    }and lets say there is a method that return an object of Test (base class), so is it possible to write
    Test2 t=getTestObj(); // i-e subclass holding base class objectif its not.. how can we do so? so that derived class should hold base class object....

    sorry..
    here is how it goes
    i have a function a class
    public Test getObj() {
    // code
    }The constraint is that i cant change the implementation of this above function.
    Now when i call this function, it returns me a Test object. But i cant do
    Test t=getObj();because the Test class is written purely in java whereas i want to use write a new Test class that implements the same functionality [using the above given function] in JNI.
    so what i did, i created a new package [nativ] and created a class "Test" in that. But since i have to use the function that returns me Test and not "nativ.Test", so what i did, i inherited nativ.Test from "Test" so that the object might resolve the reference.
    So this is it.. that i cant modify the function and i need some way to do it.. plz reply

  • Can JVM security policy be modified to access field values of private field

    Can JVM security policy be modified to access field values of "private" field in a Class?

    See http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html#ReflectPermission.
    Note that you will have to use reflection to access the fields once the security policy allows you to supress the access controls.
    Chuck

  • How to call a Derived call fucntion with a base class object ?

    Hi all
    i am working on a JNI interface to Java, and in the process of simulating a C++ behaviour in java
    so i need some help form you people, in this regard.
    here is a c++ code, i need a equivalent fucntionality in java , to put it one word, the question is
    how to implement the dynamic_cast functionality in java, as java also has virtual fucntions, i think
    this should be possible, if it is not, what is the alternative
    class Base
    public:
         Base()
         ~Base()
         virtual void F1()
              cout<<"The BASE::F1() is called"<<endl;
         virtual void F2()
              cout<<"The BASE::F2() is called"<<endl;
    class Derived : public Base
    public:
         Derived()
         ~Derived()
         virtual  void F3()
              cout<<"The Derived::F3() is called"<<endl;
         virtual void F4()
              cout<<"The Derived::F4() is called"<<endl;
    Base * GetDerived()
         return new Derived();
    int _tmain(int argc, _TCHAR* argv[])
         Base *ptr = NULL;
                    ptr  = GetDerived();
         Derived *dPtr = dynamic_cast<Derived *>(ptr);
                    dPtr->F3();
    }regards
    pradish

    Just to clarify a point that I consider important--the distinction between references and objects:
    Your subject is: How to call a Derived call fucntion with a base class object ? The answer to that is: You cannot. It is completely impossible in Java. If you have a base class object, the derivced class' methods are not present. On the other hand, if you have a compile-time reference of the parent type, but at runtime it happens to point to an instance of the derived class, then, as pointed out, you can cast the reference. (Note that casting does not apply to objects.)

  • How to use reflection to get base classes protected field

    I have one base Base classes which have protected fields and public get method to get the field.
    class Base
    protected int proField;
    public int getProField(){return proField;}
    Class Derive extends base class Base
    class Derive extends Base implements OtherInterface
    public void funtion(){};
    Now I have an instance of Derive, how can I use reflection to get the protected field inherited from Base. It seems Java Reflection only give runtime accessibility to public field and decleared field, protected-inherited field is excluded.
    Thanks
    Lei

    as the last poster said, traverse up the class hierarchy.
    ex:
    private void doSumfinToField(String fieldName throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
    Class clazz = getClass();
    Field field = findFieldInClass(clazz, fieldName);
    //field.doSumfin;
    private Field findFieldInClass(Class clazz, String fieldName) throws NoSuchFieldException {
    try { // to find the field in this class    
    return clazz.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
    // if we don't have a superclass, continue
    if (clazz.getSuperclass().equals(Object.class)) {
    throw e;
    // check in the superclass
    return findFieldInClass(clazz.getSuperclass(), fieldName);
    }

  • Base class vs derived class

    We have entity classes that we use to access our database. We have subclasses derived from these entity classes that apply business rules. For instance, the base class AddressEntity has a
    setAddress2(string) that AddressEntity.select() uses to set a class variable with data retrieved from the database. The derived class Address also has a setAddress2(string) method that puts restrictions on the length of the data. I want the AddressEntity.select() method to use the base class method AddressEntity.setAddress2(). I've tried using this.setAddress2() in AddressEntity.select() but the derived class method is still used. Any suggestions?
    Thanks,
    Joe

    If you need to call some methods on the base class sometimes and some methods on the derived class other times, but using the same object, then yes dubwai is right you should revisit your Object hierarchy.
    One simple way to do what you are asking is to have your method(s) look like this:
    void setAddress2(String sAddress) { setAddress2(sAddress, true); }
    void setAddress2(String sAddress, boolean bRestrictLength) {
      // real method
    }then you could just look at the variable bRestrictLength to see if you need to restrict the length, and have it default to true. In this way you can use overloading to solve your problem.

  • Base class/Derived class

    Hi all,
    I have
    class Base {
    int a;
    class Derived{
    int b;
    now if i do
    Base X = new Base();
    Derived D = new Derived();
    It Doesn't allow me to do D=X
    But it does allow me to do X=D.
    whats the reason behind it. And what actually happens when i do X=D , does the copy constructor gets called ?
    Thanx

    Manthana wrote:
    Hi, u said
    the value of X becomes the reference to the instance of Derived that you created when you called "new Derived()".
    So now i can access attributes of derived class from the reference X right X.b
    But i cant do X.b
    Why?Please spell out words like "you". It makes things easier to read. :)
    With Derived extending Base, you could say:
    X = D;
    X.a = 5;Because the compiler and runtime see X as a reference to a Base object, you can only access variables/methods defined in Base. Since X is declared as being a reference to Base, you always know that 'a' is defined. 'b' wouldn't be defined for X if you said:
    X = new Base();
    X.b = 52;So, in order to access the b, you'd have to access it with something declared as a reference to Derived, such as 'D':
    D.b = 10;You could say:
    X = D; // Line 1
    Derived d2 = (Derived)X;
    d2.b = 10;But, then you'll get a ClassCastException if X is only referring to a Base object [e.g., if Line 1 was "X = new Base();"], not to a Derived object.

  • How to access the attributes in an object using TestStand.?

    hi,
    I have a class named Status in C# that has 2 data members. There is another Class named Parameter and it has functions that return objects of type Status.
    I made the DLL of the class Parameter. Then i added that class to NI TestStand and called a fucntion and that function is returning an object of type Status.
    Is there any way by which i can access the Data Members of the returned Object in TestStand ??
    Thanx in advance
    Solved!
    Go to Solution.

    Yes, there is another alternative. If you make Status a value type (i.e. a struct in C#) then you can tell teststand to store it in a corresponding TestStand data structure rather than an object reference variable. This works even for private fields in your struct. To do this:
    1) First make Status a value type and make whatever other changes are necessary in your code to account for this (value types are copied when passed by value to another method, if this is not what you want you will need to pass them by reference - i.e. ref keyword in C#).
    2) Recompile your assembly.
    3) In the TestStand .NET module specification panel you should now see a new button next to the expression for the return value of type Status that looks like the TestStand data type icon. Push that button and it will prompt you to create a TestStand custom data type that corresponds to the .NET type. Select to save the type in MyTypes.ini type palette file. You only need to do this once. Once the type is in your MyTypes.ini type palette file it will be available from then on and you only need to update it if you change the .NET type.
    4) Create a local variable of the TestStand Custom data type instead of Object Reference. Note that you can expand it and see the properties underneath.
    5) Use this new local variable to store the Status return value. TestStand will copy/update the properties of the variable to correspond to those of the .NET struct that the method returns.
    NOTE: You can also just store the individual fields of a struct in separate variables by expanding the return value of type Status once it's a struct and specifying a separate variable for each field rather than creating a TestStand custom data type.
    Keep in mind that TestStand is making a copy when you store a struct this way so changes to the struct after this will not be reflected in the copy.
    Hope this helps,
    -Doug

Maybe you are looking for

  • ISR/Adobe Sending back fields from BADI in event request_check

    Dear Forum, Within my BADI implementation I want to alter some form data, after some user data has been entered. This applies to calculated fields from rather complex HR related data. Far to complex for Formcalc, but definitly as a response to user i

  • Installing GI 11gR2 11.2.0.3 on RHEL5U6

    Hi, Would like to find out if anyone has successfully implemented GI 11gR2 11.2.0.3 on RHEL5U6 with SAN storage? My team is trying to install this and we are encountering issues. Would like to know, what's your configuration like for udev rules.d, mu

  • Aligning result with negative values

    Hi, I have to align the amount in the report. My problem here is, when the report displays negative values, the amount misaligned. Can you help me on this one? thanks!

  • How the callback works in the events?

    Hi, I am in doubt that how the callback will occur internally? Consider i am having one delegate and one static event for it.  Ex: public delegate void raiseDelegate(String someDesc); public static event raiseDelegate callComlpetedEvent; And also Con

  • HP 4120 Lync Phone Edition - Ringer Volume Level Can Not be controlled when a second call comes in for a workflow

    Here is the scenario we are experiencing with our HP 4120 Lync phones running the latest available firmware (4.0.7577.4455) 1) A User has an HP 4120 phone and is a member of a workflow/response group which is setup with attendant routing method. 2) T