Setting private fields from Parent class.

Hi all, I have what seems to be a weird situation to me.
Basically I have two classes:
import java.lang.reflect.Field;
public class Parent {
     protected void ensureDefaults() {
          Field[] declaredFields = getClass().getDeclaredFields();
          for (Field field : declaredFields) {
               Object fieldValue = getDefaultValueForType(field.getType());
               try {
                    System.out.println("defaulting field - name: " + field.getName() + " | this: " + this);
                    field.set(this, fieldValue);
               } catch (Exception e) {
                    e.printStackTrace();
     private Object getDefaultValueForType(Class<?> type) {
          Object defaultValue = null;
          if (type.isAssignableFrom(String.class)) {
               defaultValue = "default";
          } else if (type.isAssignableFrom(int.class)) {
               defaultValue = -100;
          return defaultValue;
public class Child extends Parent {
     private String name;
     private int age;
     public Child() {
          ensureDefaults();
     public String getName() {
          return name;
     public void setName(String name) {
          this.name = name;
     public int getAge() {
          return age;
     public void setAge(int age) {
          this.age = age;
// Test Case
import junit.framework.TestCase;
public class ChildTest extends TestCase {
     public void testEnsureDefaults() {
          Child child = new Child();
          assertEquals("default", child.getName());
          assertEquals(-100, child.getAge());
}The odd thing to me is that the output looks like:
defaulting field - name: name | this: Child@7431b9
java.lang.IllegalAccessException: Class Parent can not access a member of class Child with modifiers "private"
... more exception ...
defaulting field - name: age | this: Child@7431b9
java.lang.IllegalAccessException: Class Parent can not access a member of class Child with modifiers "private"
... more exception ...
As you can see, it doesn't like me setting (or getting for that matter - tried that) these fields because they're private. However, if you look it's saying that "this" is a Child, so shouldn't those fields be accessible? Shouldn't ensureDefaults be executed as if it was being called by the Child instance?
Obviously, I can try to use the accessor methods, but that means creating strings for method names, and then looking for the methods. I'd like to avoid this and it seems to me this should work, no?
Another odd thing is that if I change the fields in Child to protected, it works fine.
Also, I'm not sure if this is important (I don't know enough about security managers to know if they're different platform to platform, version to version), I'm on a Mac OSX 10.4.11 and:
java version "1.5.0_13"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_13-b05-241)
Java HotSpot(TM) Client VM (build 1.5.0_13-121, mixed mode, sharing)
Any help with this would be greatly appreciated.
Thanks,
Eric

jschell wrote:
As you can see, it doesn't like me setting (or getting for that matter - tried that) these fields because they're private.Myself I don't like it because it suggests a design problem which is associated with understanding that although a child is a parent that doesn't mean that a parent is a child.
I understand that, but I don't see how this actually breaks that. The Child is executing a method that is passed down to it from it's Parent, but it's executing it as itself - by that I mean it's not looking at anything that it can't already look at, or at least I thought it was.
Shouldn't ensureDefaults be executed as if it was being called by the Child instance?No.Ok, I thought it was. Can you please explain this a bit more, I want to understand it.
>
Another odd thing is that if I change the fields in Child to protected, it works fine.If you messed with reflection some more you could get to to work even with private. How exactly? I really don't want to bypass any security measures (by settings accessible or using a different security manager, or anything like that). As I mentioned in my last post, what I want to do really is nothing more than a nice way to have a generic toString or hashCode method, if it's not possible to do it nicely - within java's default constraints, I'd rather not.
>
However in general the idiom would still be wrong.I'm moving more towards using beans anyway, so I plan on just calling accessor methods which corrects the "wrong idiom" right?
Thanks for all the help,
Eric

Similar Messages

  • How to get private fields from super class?

    Hi.
    I must get protected and private fields from a class. I know that sounds werid but I have a very good reason for doing so, ask if you want.
    I have tried the getDeclaredField(String) method, but it apparently doesn't return the fields declared by the super classes.
    What's the smartest solution to this?
    Thank you all.
    edit: note that the superclass hierarchy's length is 3 and that there are several classes at the bottom level.
    Edited by: bestam on Sep 24, 2009 2:05 PM

    bestam wrote:
    I do not claim I have invented a new programming language Sir, you must be mistaken. This is not turing complete.
    This is a language for describing Cards or a game's rules if you want.
    AspectJ isn't Turing complete but AspectJ is still a compiler.
    This is how I have been working :
    - I have implemented the core library in Java (what is a Player, what is an Effect, what is a Card, what is a BuildingCard, what is a Player's Turn and so on)
    - It also includes packages dedicated to service, able to retrieve and send data to the clients via sockets.
    - Then I have "hardcoded" a dozen of specific cards in Java, for testing and validating the core library. I have been doing so by extending the BuildinCard's class for example.
    - But my ultimate goal is not to code thoses 1.000+ cards of the game in Java. I chosed to design a little language so that I would end up writing cards faster. While I'm traversing the syntactical tree representing the card, I feed the card's fields one by one. Some of them are quite primitive, some other are more complex and have a recursive nature for instance.
    Providing detail for how you implemented it doesn't change anything about what I already said.
    Thus, this is not really a compiler as it doesn't transform a text in language A into a text in language B.
    You really need to understand more about what "compilers" and certainly compiler theory do before you decide what they can and cannot do.
    And your statement still does not change what I said.
    Is this wrose than the bean design pattern from JSP ? I'm not sure.
    Bean design? A "bean" has almost zero requirements.
    Aside of that, it's a bit harsh to be told "read the fucking manual" while I have written my first compiler some years ago.Not sure who that was directed. I suggested some reading material on compiler theory.
    If you think that your idea is ideal then knock yourself out. Since I doubt I will end up seeing it in anything that I must maintain it doesn't matter to me. But you did in fact ask what the best solution was.

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

  • How can I casting from parent class to children class

    Dear,
    Could someone help me to casting from parent class to children class.
    I have class like this
    class parent{
    String name;
    String id;
    public String getId() {
    return id;
    public void setId(String id) {
    this.id = id;
    public String getName() {
    return name;
    public void setName(String name) {
    this.name = name;
    class children extends parent{
    String address;
    public String getAddress() {
    return address;
    public void setAddress(String address) {
    this.address = address;
    public children() {
    public children(parent p) {
    //Do init super class here
    In the constructor
    public children(parent p) {
    //Do init super class here
    I like to init super class by object p (this is instance of parent class). The way to do is using:
    public children(parent p) {
    super.setId(p.getId());
    super.setName(p.getName());
    But I don't like this, because, for example I have parent class with over 30 proberties, it take time to do like that.
    There are any way to use super operation to init parent class, for example super = p;
    Could you show me the way.
    Thanks alot

    If I understand your question correctly, you are in need of a copy constructor for you class Parent. A copy constructor behaves like this:
       Parent one = new Parent();
       one.setName("...");
       //... and all other properties of interest
       Parent two = new Parent(one);
       //Now two != one, but one.getName().equals(two.getName) for property name and all othersThe copy constructor is programmed in the Parent class, more later. Then for your child class you can use it as follows
       public class Children extends Parent {
           public Children(Parent p) {
              super(p);
       }There are at least 3 ways of programming a copy constructor:
    1. Just bite the bullet: type the assignment for each field this.name = p.getName()
    2. Use reflection to find all common setters/getters dynamically and assign using them
    3. Use a code generator that uses 2 to give you the code for solution 1 for you to paste in.
    If you find doing this a lot, there are frameworks that can do these mappings, like Dozer
    (PS be carefull with Date fields, don't copy the reference but create a new and equals instance, the dirty way would be this.birthdate = new Date(p.getBirthdate.getTime()); )

  • Reflection: how to get the name of a subclass from parent class?

    Suppose I have a parent class P and two subclasses S1, and S2. There's another method which has an argument of type P. Inside this method, I want to inspect the object (of type P) passed in and print its name, such as "S1" or "S2". How do you do that? I tried Class.getSimpleName(), but "P" is returned no matter which subclass objects you have. Thanks:)

    That's the same as you said last time, and I'm telling you that's not what happens when I test it:
    public class Parent {
    public class SubclassOne extends Parent {
    public class SubclassTwo extends Parent {
    public class TestGetName {
      public static void main(String[] argv) {
        showNames(new SubclassOne());
        showNames(new SubclassTwo());
        showNames(new Parent());
      private static void showNames(Parent p) {
        System.out.println("Name: " + p.getClass().getName());
        System.out.println("Simple name: " + p.getClass().getSimpleName());
        System.out.println("Canonical name: " + p.getClass().getCanonicalName());
    }prints:
    Name: SubclassOne
    Simple name: SubclassOne
    Canonical name: SubclassOne
    Name: SubclassTwo
    Simple name: SubclassTwo
    Canonical name: SubclassTwo
    Name: Parent
    Simple name: Parent
    Canonical name: ParentYou must be doing something else that you're not saying. Either that or you're expressing yourself very poorly. Why not post a simple, self-contained, compilable example of what you claim is happening?

  • How to listen to user actions in child class from parent class?

    Hi,
    I have a basic custom class ChildCustomForm that include a JTextField. In order to know what user types, I add a listener to
    this textbox:
    textField.addKeyListener( new KeyAdapter()
                @Override
                public void keyPressed( final KeyEvent e )
                    //user typed something
                    userTyped = true;
             });Now I have another parent class that uses ChildCustomForm, and parent class has to know once user types, then set
    its own userTyped flag.
    My problem is: since I added listener in child class, I cannot get textfield and add listener again in parent class, so parent class will not be able to know as soon as user types (polling is not a good solution here).
    I am wondering if there is a way to do this?
    regards,

    jack_wns wrote:
    I have a basic custom class ChildCustomForm that include a JTextField. In order to know what user types, I add a listener to
    this textbox:You want to listen for input into the textbox, correct? This may take the form of keyboard input, or could be a paste-text event in which case your keylistener will miss it. I recommend that you look into a DocumentListener here so you will catch any changes, be they keyboard or cut or paste.
    My problem is: since I added listener in child class, I cannot get textfield and add listener again in parent class, so parent class will not be able to know as soon as user types (polling is not a good solution here).The observer pattern may work here.

  • Overriding JAXB annotations from parent class

    Helllo everyone, I'm cross posting this here because I origanally asked in the from forum. My apologies...
    I'm attempting to override a JAXB annotation. Internally, we use the field. Externally, we do not want the field to appear as it is an Internal only identifier. I have a class and a subclass. MemberPK is the internal version we use on our internal webservices, and ExternalMemberPK is the one we want to serialize externally.
    When I look at the generated WSDL below, customerID still appears. THANK you, for any help, even if it's just a guess, it could very well push me in the correct direction. I'm using Apache CXF 2.3.1, Sun Java 6 latest on Glassfish latest. Suggestions welcome on 'a better way' to do this as well. Thanks!
    @XmlType(propOrder = {})
    @XmlAccessorType(XmlAccessType.PROPERTY)
    public class MemberPK implements Serializable {
    private static final long serialVersionUID = 5L;
    private Integer customerId;
    private String customerName;
    ...other fields
    * @return the customerId
    public Integer getCustomerId() {
    return customerId;
    * @param customerId
    * the customerId to set
    public void setCustomerId(Integer customerId) {
    this.customerId = customerId;
    @XmlType(propOrder = {})
    @XmlAccessorType(XmlAccessType.PROPERTY)
    public class ExternalMemberPK extends MemberPK {
    private static final long serialVersionUID = 5L;
    * {@inheritDoc}
    @Override
    @XmlTransient
    public Integer getCustomerId() {
    return customerId;
    }

    Helllo everyone, I'm cross posting this here because I origanally asked in the from forum. My apologies...
    I'm attempting to override a JAXB annotation. Internally, we use the field. Externally, we do not want the field to appear as it is an Internal only identifier. I have a class and a subclass. MemberPK is the internal version we use on our internal webservices, and ExternalMemberPK is the one we want to serialize externally.
    When I look at the generated WSDL below, customerID still appears. THANK you, for any help, even if it's just a guess, it could very well push me in the correct direction. I'm using Apache CXF 2.3.1, Sun Java 6 latest on Glassfish latest. Suggestions welcome on 'a better way' to do this as well. Thanks!
    @XmlType(propOrder = {})
    @XmlAccessorType(XmlAccessType.PROPERTY)
    public class MemberPK implements Serializable {
    private static final long serialVersionUID = 5L;
    private Integer customerId;
    private String customerName;
    ...other fields
    * @return the customerId
    public Integer getCustomerId() {
    return customerId;
    * @param customerId
    * the customerId to set
    public void setCustomerId(Integer customerId) {
    this.customerId = customerId;
    @XmlType(propOrder = {})
    @XmlAccessorType(XmlAccessType.PROPERTY)
    public class ExternalMemberPK extends MemberPK {
    private static final long serialVersionUID = 5L;
    * {@inheritDoc}
    @Override
    @XmlTransient
    public Integer getCustomerId() {
    return customerId;
    }

  • Problems accessing child swf from parent class

    First off: Hi. I'm new - to the forum and to Flash.
    I'm currently writing a flash app that requests a XML feed
    from a Java controller and loads child swfs into various parts of
    the stage based on the settings/URL details received from the XML
    feed.
    Its nearly there and I've got my head round a couple of weird
    things, but theres one thing left that I've found impossible to
    solve. Once the loader class has loaded the swf, it can't access
    its methods or set its variables and the child can't access the
    parent either (or access the parent's variables full stop). From
    what I've read this should be possible. Heres some of my code plus
    pseudo code:
    Note the Panel class is not linked to a symbol and uses
    composition to act like a movie clip, rather than inheritance.
    quote:
    class Panel{
    function Panel(owner:MovieClip, insName:String,
    depth:Number){
    initiates properties etc....
    panelMovie = owner.createEmptyMovieClip(insName,depth);
    listener.onLoadComplete = mx.utils.Delegate.create(this,
    scheduleModule);
    loader.addListener(listener);
    loader.loadClip(moduleX.url, panelMovie);
    function scheduleModule(){
    trace(panelMovie.key);
    trace(panelMove.keyTest());
    panelMovie.key = "dave";
    trace(panelMovie.key);
    Child swf:
    quote:
    var key:String = "test";
    As you can see I create an empty movieclip which I store a
    reference to in this class under the field "panelMovie". I then use
    this (instead of target_mc like you might do with an event handler)
    to try to access the child swf. The output is:
    trace(panelMovie.key); = "test" (Works fine)
    trace(panelMove.keyTest()); = (Nothing returned)
    panelMovie.key = "dave";
    trace(panelMovie.key); = "test" (Previous line = no effect)
    Is this something related to using a class? Really would be
    preferentially to keep all code outside of the fla.
    I've also tried a lot of different combinations of _root,
    _parent and _levelx. None of which I truly understand.
    Any help would be much appreciated! Plus any good tutorial
    links on timeline and referring to objects in it!
    (Couldn't find the code tag/button...)

    >>trace(panelMove.keyTest()); = (Nothing returned)
    You have panelMove here instead of panelMovie
    Dave -
    Head Developer
    http://www.blurredistinction.com
    Adobe Community Expert
    http://www.adobe.com/communities/experts/

  • Accessing super class  private variables from derived class

    posted November 01, 2005 08:20 PM Profile for kenji mapes Email kenji mapes Send New Private Message Edit/Delete Post Reply With Quote Assume I have a default and a param constructor in both a subclass and a super class. The members are private.
    So after validation logic in the sub class param. constructor, I want to access an instance variable of the super class's default constructor to set the subclass's matching variable to the default in the super class.
    Is there anyway I can do this. Of course, I have inherited setters and getters.
    Thanks.

    posted November 01, 2005 08:20 PM Profile for
    kenji mapes Email kenji mapes Send New Private
    Message Edit/Delete Post Reply With QuoteI suppose this is the result of an attempted crossposting from another forum. :)

  • Is there a way to reference a private variable from one class in another?

    My first class starts off by declaring variables like so:
    class tStudent {
      // declare student name, id, grades 1 & 2, and gpa
      private String fname, lname, g1, g2;
      private int id;
      private double gpa;
      // define a constructor for a new student
      tStudent () {fname=lname=g1=g2=null; id=-1; gpa=0.0;}
      // define methods for manipulating the data members.
      // readStudent: reads information for just one student
    public void read (Scanner input) {
          fname = input.next();
          lname = input.next();
          id = input.nextInt();
          g1 = input.next();
          g2 = input.next();
    }And the second class:// tStudentList: for a list of students
    class tStudentList {
      private int nStudents;
      private tStudent[] list;
      // constructor for creating student list
      tStudentList() {
          list = new tStudent[36];
          for (int i=0; i < 36; i++) list=new tStudent();
    // read the individual students into the student list
    public void read(Scanner scan) {
    nStudents=0;
    while (scan.hasNext()) {list[nStudents++].read(scan);}
    // display the list of all students - fname, lname, id, g1, g2 and gpa
    // with an appropriate header so the output matches my sample //output
    public void print() {
    Is there a way to reference the variables in the first class to use in the second? Specifically in the last section of code where I am going to print the list.

    Not without resorting to reflection hackery. If the fields are private (and are supposed to be), then that means "don't allow access to these to outsiders of this class" by design.
    So if you really meant them to be accessible, then don't use private, or provide public accessors for them.

  • How to set a field from an assigment block as required for a BP creation

    Hi,
    I have the following requirement.
    On employee master data creation, I want to make field System user mandatory in Employee creation.
    Iam using Component: BP_EMPL View: BP_EMPL/EmployeeDetails
    It happens that this field is inside an assignment block (BP DATA, view: InternetUser).
    By screen configuration I am not able to set it as a mandatory assignment block or as a mandatory field inside the assignment block. Is there any way to solve this by configuration?
    In case of development is better to use an ABAP exit on save moment or is there any option using BSP development?
    Thanks.
    Susana Messias

    Hi Susana!
    Please see also these posts related to your issue:
    [Different fields depending of BP Role or any other field|Different fields depending of BP Role or any other field]
    Here some relevant notes:
    Note 1259940 - Authority check for accounts depending on roles
    Note 1260695 - Data set-specific screen control
    Note 1097651 - How to use the Account Life Cycle
    Note 999092 - CRM WebClient: Field & screen modification
    Best regards
    Arno

  • Setting native code from a class of a class passed in...

    I hope this makes sense, and its probably a stupid question but here it goes.
    I have a native function that takes in a java class. I can call the getters of this class from the native code to get values to fill out my c structure just fine, but conceptually I am not 100% how to call the getters of a class that is part of the other class I passed in. Basically i have something like this:
    the java call to the native being:
    public native void setJSource(JSource theSource);
    JNIEXPORT void JNICALL Java_AbfaRegion_setJSource
      (JNIEnv *env, jobject thisObj, jobject someVarsObj)
              jclass clazz;
              jmethodID mid;
              jint val;
              clazz = (*env)->GetObjectClass(env,someVarsObj);
              mid = (*env)->GetMethodID(env,clazz, "GetHeight", "I");
              val = (*env)->CallIntMethod(env,someVarsObj, mid);
              //put val into my struct
              mid = (*env)->GetMethodID(env,clazz, "GetWidth", "I");
              val=(*env)->CallIntMethod(env,someVarsObj, mid);
              //put val into my struct
    }I know how to do this...but what if I had a class say:
    class myClass
        JSource theSource; //has its own getters and setters like GetHeight
        int someVal;
        double anotherVal;
        public native void setMyClass(myClass theClass)
        int GetSomeVal()
          return this.someVal;
        int GetAnotherVal()
          return this.anotherVal;
        void SetSomeVal(int iSomeVal) 
          this.someVal=iSomeVal;
        void SetAnotherVal(double dAnotherVal)
          this.anotherVal=dAnotherVal;
    }and then suppose in the native setMyClass I would like to get the height of the jsource of myclass, how can i do that in native code, do I have to use findclass or something?
    Thanks for any help here, sorry if its a dumb question..
    -Shane

    For any class whose methods you are going to call, you need to first get a reference to the "class" record. So if you have an outer class, and have looked up its class record, and called a getter, and been returned an object (phew!):
    You need to now look up the class for the inner object; you can then look up the the methods and call them.
    JNI supports two ways to look up class:
    FindClass, where the key argument is the fully-qualified class name.
    GetObjectClass, where the key argument is an object reference.

  • Re-set up icloud from parents account to childs own acct

    We set up our daughters ipad under our icloud, apple id, but realize now we should've made her own new account.  How do we change this?  As set up now, all of my contacts are on her ipad, and I am getting all her emails from games she plays.

    You can create and use different iCloud accounts on the same computer, whether they are single or multiple user.
    There is a limit of 3 accounts you can create from a device but I thought this was only iOS devices - maybe not.
    iCloud accounts can only be created using a valid email address, so I guess I'd start there to retrace what accounts you have.
    My Apple ID and iForgot.com may be useful sites for you.

  • Adf-Struts/JSP/BC4J- and setting date fields from jsp

    Hi,
    I'm working with the new ADF Frameworks (JDev 9.0.5.1) and ran into some questions regarding exception handling using BC4J, Struts and JSPs.
    I have a DATE column in database and an entity and VO with a datefield with type oracle.jbo.domain.Date.
    My JSP shows a textfield and the user should enter a valid date. Everything fine, until date is of wrong format or contains illegal characters...
    Problem:
    ADF tries to do a setAttribute on the datefield in VO row which expects a parameter with type oracle.jbo.domain.Date. When the user entered e.g. "NiceWeather" as date, I get an IIlegalArgumentException while converting to the correct Date format. This exception isn't thrown by bc4j as AttrValException and therefore my JSP renders a global error instead of a message directly behind the date field.
    I tried to validate the datefield in my DataForm and in my Action in the validateModelUpdates() method, but with no fitting solution.
    Any ideas how to validate a datefield with adf/struts/jsp/bc4j?
    Thanks for your help!
    Torsten.

    Torsen - In the first instance I'd recommed that you try and handle it declaritively using the Struts Validator Framework . See http://otn.oracle.com/products/jdev/howtos/10g/StrutsValidator/struts_validator_howto.html
    There is a section in there on how to use the validator with ADF databound pages and you can check the format the user enters via generated JavaScript.
    Also check out the matching sample project:
    http://otn.oracle.com/sample_code/products/jdev/10g/ADFandStrutsValidator.zip - this has a data field check on it as well

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

Maybe you are looking for

  • How can I get a downloaded application to run when security settings won't allow it?

    I am trying to run an application today that I downloaded from Safari. I run this every single business day by control - clicking to open it in Finder. Today it won't allow me to open it all because of my security settings. When I temporarily remove

  • New Income tax slab for FY 2013-14 / AY 2014-15-Not working in SAP

    Dear Consultants, According to Indian Govt New Income tax slab for FY 2013-14 / AY 2014-15, Taxable Income in 10% slab maximum tax will be Rs 28000 (taking 2000 tax credit into consideration) is there any SAP note to be apply for this condition, Plea

  • Add a Print button to a Report Page

    I'm trying to add a Print button to a report page to render the page in printer-friendly mode and then give the user the option to send to a printer. I started with just trying to add a print button. I added a button to the region and added to the bu

  • Need help with INSTEAD OF trigger on view

    Hi, I am trying to use INSTEAD OF on a view because I will be updating the calling table in my trigger, which will cause mutation.  I need to update attribute7 of another record based on the new attribute7 of the current record (record being updated

  • Link on portal

    Hi experts, I want to create a page where i can stored many url links. I want for example that it displays "google" for url "www.google.com" and when i click on 'google' it opens the website in another page. I tried created a URL iView but it display