Skip to Main Content

Japanese

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to access the parent class variable or object in java

user587485Dec 11 2013

Hi Gurus,

I encounter an issue when try to refer to parent class variable or object instance in java.

The issue is when the child class reside in different location from the parent class as shown below.

- ClassA and ClassB are reside in xxx.oracle.apps.inv.mo.server;

- Derived is reside in xxx.oracle.apps.inv.mo.server.test;

Let say ClassA and ClassB are the base / seeded class and can not be modified. How can i refer to the variable or object instance of ClassA and ClassB inside Derived class.

package xxx.oracle.apps.inv.mo.server;

public class ClassA {

    public int i=10;

}

package xxx.oracle.apps.inv.mo.server;

public class ClassB extends ClassA{

    int i=20;   

}

package xxx.oracle.apps.inv.mo.server.test;

import xxx.oracle.apps.inv.mo.server.ClassA;

import xxx.oracle.apps.inv.mo.server.ClassB;

public class Derived extends ClassB {

    int i=30;

    public Derived() {

       System.out.println(this.i);                  // this will print 30

       System.out.println(((ClassB)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassB

       System.out.println(((ClassA)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassA

    }

    public static void main(String[] args) { 

        Derived d = new Derived(); 

    }

}

Many thanks in advance,

Fendy

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 8 2014
Added on Dec 11 2013
0 comments
913 views