Access super class private variables

class A
private int i,j;
A()
i=j=20;
public void show()
System.out.println(i+" "+j);
class B extends A
int k;
B()
super();
k=20;
public static void main(String args[])
B b=new B();
b.show();
In the above program, when a instance of class A is created, the memory is allocated for 2 private integer variables(i and j in this case) 8 byte of memory gets allocated and the referance is returned to the object.
ex:
A a=new A();
a contains the address of memory allocated for 2 integer variables.
In this code there is another class called B which contains only one variable of it's own.when a object is creted for class B only 4 byte of memory is allocated and the reference is returned.
ex:
B b=new B();
b contains address of 4 byte of memory allocated.
my doubt is when the B's constructor is called,it inturn calls super(),
where the variables are intialized. variable (i,j) does not exist in memory and how are they getting initialized.are they created at runtime and getting initialized.Though B has no explicit control over these variables it can able to access their values.How is that possible??

Can you please stop creating multiple threads with the same question. There is already a discussion in your other thread. Please don't waste our time.
http://forum.java.sun.com/thread.jspa?messageID=4063146#4063146
Kaj

Similar Messages

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

  • Accessing a class private variable in the main timeline

    Greetings,
    noob question.
    Here's my main class:
    package
         import flash.external.ExternalInterface;
         public class main
             public function main()
             public function check_DVBViewer()
                 ExternalInterface.call("check_DVBViewer","test");
                 ExternalInterface.addCallback("AutoIT",AutoIT);
             private function AutoIT(my_msg:String)
                     // here we get the callback string
    in the timeline I have a dynamic text box named my_textbox:
    var my_test:main = new main();
    my_test.check_DVBViewer();
    my_textbox.text = ???????
    Basically the class waits for the callback variable (my_msg).
    The problem is: I need to set the dynamic textbox text to my_msg variable.
    How can I access it?
    I know I can access a public var in the timeline with functioname.variable but I can't define a public var inside a function, right?
    Thank you very much for your time.

    dispatch an event when the string is ready:
    package
         import flash.external.ExternalInterface;
         public class main
    private var msg:String;
             public function main()
             public function check_DVBViewer()
                 ExternalInterface.call("check_DVBViewer","test");
                 ExternalInterface.addCallback("AutoIT",AutoIT);
             private function AutoIT(my_msg:String)
                     // here we get the callback string
    msg=my_msg;
    dispatchEvent(new Event("stringready"));
    public function get msgF():String{
    return msg;
    in the timeline I have a dynamic text box named my_textbox:
    var my_test:main = new main();
    my_test.addEventListener("stringready",f);
    my_test.check_DVBViewer();
    function f(e:Event):void{
    my_textbox.text = my_test.msgF;

  • Query: Accessing super class

    hi friends ,
    i have a small doubt on accessing super class using super keyword.
    does the use of super as super(super(super(i))); work properly
    and what would be the result.
    kindly guide me..........
    jay

    What do you expect that to do? Is that supposed to be a call to a super constructor? (and then super-super, and then super-super-super).
    In any case, you can only call things from the immediate superclass (the parent). If you think you need to call the superclass' superclass (the grandparent), you likely have a bad design.
    What are you trying to do?

  • Accessing Super Class of Super Class

    Consider the following classes
    Class A {
    print() {
    System.out.println("Class A Called");
    Class B extends A {
    print() {
    System.out.println("Class B Called");
    Class C extends B {
    print() {
    System.out.println("Class C Called");
    How can I call the print method of class A while working in class C ? Please state all possible solutions.
    Can it somehow be done using super ?

    RZP wrote:
    Consider the following classes
    Class A {
    print() {
    System.out.println("Class A Called");
    Class B extends A {
    print() {
    System.out.println("Class B Called");
    Class C extends B {
    print() {
    System.out.println("Class C Called");
    How can I call the print method of class A while working in class C ? Please state all possible solutions.
    Can it somehow be done using super ?Here is one possible solution.
    I really don't understand the ramifications of reflection... and am not familiar with OOP design... but reflection seems to enable a programmer to avoid OOP design principals as well as type-checking. While I like reflection, most of my readings suggest to rarely use it.
    public class Main {
      public static void main(String[] args) {
        try {
          new C(789).print();
        } catch(Exception e) { e.printStackTrace();  }
          static class A {
            protected A a;
            protected int id;
            public A(A a, Integer id) {
              this.a = a;
              this.id = id;
            public A(int id) { this.id = id; }
            public void print() {
              System.out.println("Class A called... from a " + a.getClass().getCanonicalName() + " using the original instance with id = " + a.id);
        static class B extends A {
          public B(A a, Integer id) { super(a, id);  }
          public B(int id) { super(id); }
          public void print() { System.out.println("Class B called...");   }
        static class C extends B {
            public C(A a, Integer id) { super(a, id); }
            public C(int id) { super(id); }
            public void print() {
                try {
                    System.out.println("Class C called...");
                    Object obj = getClass().getSuperclass().getSuperclass().getConstructor(A.class, Integer.class).newInstance(this, -111);
                    obj.getClass().getMethod("print", null).invoke(obj, null);
                } catch (Exception e) {
                    e.printStackTrace();
    }Anyway, I think that enables one to invoke overridden methods in super classes, regardless of how "high-up" they are in the class heirarchy (without having to use a new object to do it). Use that idea in an interview at your own risk but just not in interviews for the same position I am trying to get...
    Edited by: dpxqb on Apr 17, 2010 4:43 AM

  • How to access super class's super class

    Hello every one.
    I have a question.
    if I have a class like:
    public class A {
    void methoda() {
    void methodb() {
    and a class B extends A and override A's methoda
    public class B extends A {
    void methoda() {
    and a class C extends B which want use A's methoda.
    public class C extends B {
    // and here I want to use class A 's methoda,how can I do?
    thanks a lot

    Try the following. When run it eill print out:
    [In class C] A:B:C
    Now calling A's method: [In class A] A and i is 500Which is what you want right?
    public class TestSuperSuper {
        public static void main (String[] args) throws Exception {
            C c = new C();
            c.setName("A", "B", "C");
            c.setI(500);
            c.methodA();
        static class A {
            String aName;
            int i;
            public void methodA(){
                System.out.println("[In class A] " + aName + " and i is " + i);
            public void setName(String aName){
                this.aName = aName;
            public void setI(int i){
                this.i = i;
        static class B extends A {
            String bName;
            public void methodA(){
                System.out.println("[In class B] " + aName + ":" + bName);
            public void setName(String aName, String bName){
                this.aName = aName;
                this.bName = bName;
        static class C extends B {
            String cName;
            A wrappedA;
            public C(){
                wrappedA = new A();
            public void methodA(){
                reflectOnA();
                System.out.println("[In class C] " + aName + ":" + bName + ":" + cName);
                System.out.print("Now calling A's method: ");
                wrappedA.methodA();
            public void setName(String aName, String bName, String cName){
                this.aName = aName;
                this.bName = bName;
                this.cName = cName;
            private void reflectOnA(){
                try {
                Field[] aFields = wrappedA.getClass().getDeclaredFields();
                for (int i = 0; i < aFields.length; i++){
                    Class fldType = aFields.getType();
    if (fldType.isPrimitive()){
    if (fldType.getName().equals("int")){
    aFields[i].setInt(wrappedA, aFields[i].getInt(this));
    else {
    // now do the other primitive type tests here
    else {
    aFields[i].set(wrappedA, aFields[i].get(this));
    catch (Exception e){
    System.err.println(e);
    The main thing here is that in class C you have an instance variable called wrappedA which is an instance of A and the method called reflectOnA(). Basically, what this method does is it will set all the fields in wrappedA to the same values that this object has so that it would look like that wrappedA is somewhat the same as this object. You will call this method whenever you want to call your superclass' superclass' method.
    Hope this helps.

  • Composition in java : how to access super-class from sub-class

    I have 3 classes related by composition
    class A{
    B b = new B();
    class B{
    List<C> cList = new ArrayList<C>();
    in class C{
    getSample(){
         //Try to access class A     
    how can I access A from class C ?
    Any help is appreciated!

    well, 'Id' is known only to class A, and class C has a getSample() which is called in class A.
    class A{
    B b = new B();
    getID(){
    return id;
    b.getC().getSample();
    class B{
    List<C> cList = new ArrayList<C>();
    class C{
    getSample(){
    if() {
    //pick up value from properties file
    // format the value and parameter substitute it with 'Id' from A
    The design does seem a little weird, but I guess this is the only way to do this considering the other constraints we have ....
    TIA

  • Sub class will allocate seperate memory for super class  instance variable?

    class A
    int i, j;
    void showij()
    System.out.println("i and j: " + i + " " + j);
    class B extends A
    int k;
    void showij()
    System.out.println("i and j: " + i + " " + j);
    what is size of class B will it be just 4 byte for k or 12 bytes for i, j and k ?
    will be a seperate copy of i and j in B or address is same ?
    thank u

    amit.khosla wrote:
    just to add on...if you create seprate objects of A and B, so the addresses will be different. We cant inherit objects, we inherit classes. It means if you have an object of A and another object of B, they are totally different objects in terms of state they are into. They can share same value, but its not compulsary that they will share same values of i &j.
    Extending A means to making a new class which already have properties & behaviour of A.
    Hope this help.That is very unclear.
    If you create two objects, there will be two "addresses", and two sets of member variables.
    If you create one object, there will be one "address", and one complete set of non-static member variables that is the union of all non-static member variables declared in the class and all its ancestor classes.

  • Accessing Super Class methods

    Hi,
    If I have a Subclass that overrides a method in a superclass, is it possible to call that method from the superclass?
    Thanks

    Hi thanks for the reply, but that works for static methods, I'm trying to figure out non-static methods. Below, I want to call the method a() from the superclass using an instance of the subclass.
    class superclassA
    void a()
    System.out.println("in method a");
    class subclassA extends superclassA
    void a()
    System.out.println("in method b");
    public class overtest
    public static void main(String [] args)
    subclassA sub = new subclassA();
    superclassA.a();//non-static method a cannot be referenced from a static context
    Thanks!

  • How to pass subclass to variable of super class ?

    class /EVUIT/EXCH_PRD_GUI definition
    public section.
      methods CONSTRUCTOR
        importing
          value(I_APPLICATION) type ref to /UIT/EXCH_PRD_APP optional
          value(I_REPID) like SY-REPID .
    class /UIT/EXCH_PRD_VERT_NN_MODEL definition
      public
      inheriting from /EVUIT/EXCH_PRD_APP
      create public .
    DATA: l_vert_nn_model type ref to /uit/exch_prd_vert_nn_model.
    DATA: l_gui type ref to /uit/exch_prd_gui_vbeleg.
       CREATE OBJECT l_vert_nn_model
            EXPORTING
              I_ALV_RECORDS = gt_alv_records[].
    CREATE OBJECT l_gui
       EXPORTING
         I_APPLICATION = l_vert_nn_model
         I_REPID = sy-repid .{color}
    Problem i am facing is for l_gui the parameter i_application is of type super class of l_vert_nn_model.
    Any suggestions, how can i pass this subclass object to the parameter which is of type super class?

    Hello Trivenn
    On SAP basis release 7.00 the following coding works:
    *& Report  ZUS_OO_DUMMY
    REPORT  zus_oo_dummy.
    *       CLASS lcl_local DEFINITION
    CLASS lcl_local DEFINITION.
      PUBLIC SECTION.
        METHODS:
          constructor
            IMPORTING
              value(io_instance)  TYPE REF TO zcl_edi_uk_svcs_out. " super class
      PRIVATE SECTION.
        data: mo_instance         type ref to object.
    ENDCLASS.                    "lcl_local DEFINITION
    *       CLASS lcl_local IMPLEMENTATION
    CLASS lcl_local IMPLEMENTATION.
      METHOD constructor.
        mo_instance ?= io_instance.
      ENDMETHOD.                    "constructor
    ENDCLASS.                    "lcl_local IMPLEMENTATION
    DATA: go_super    TYPE REF TO zcl_edi_uk_svcs_out,
          go_sub      TYPE REF TO zcl_edi_uk_svcs_out_customer,
          go_local    type ref to lcl_local.
    START-OF-SELECTION.
      CREATE OBJECT go_super.
      CREATE OBJECT go_sub.
      create object go_local
        exporting
          io_instance = go_sub.
      BREAK-POINT.
    END-OF-SELECTION.
    Regards
      Uwe

  • Trouble assigning sub class to super class array

    Hi,
    I would greatly appreciate some help with the following:
    I want to assign a sub class to a super class array but the following code does not work
    where the board is comprised of the super class
         private static void makeMove( int X, int Y, int moveX, int moveY )
              ChessPiece tempChessPiece = ( ChessPiece ) board[ X ] [ Y ];
              board[ X ] [ Y ].setType( UNDEFINED );
              board[ moveX ] [  moveY  ] = tempChessPiece;
         }

    I have got this code to work but it does not appear
    to be very efficient to me as i dont recycle the
    objects.
    Any thoughts?The objects will be recycled by the garbage collector. It's very efficient so there's very little performance penalty in creating objects and releasing objects.
    Still, another alternative is to represent an empty square with null. In that case the code becomes,
    private static void makeMove( int selectedX, int selectedY, int moveToX, int moveToY ) {
       board[moveToY][moveToX] = board[selectedX][selectedY]; // piece to new position
       board[selectedX][selectedY] = null; // remove from old
    }I don't know your exact design but that should work. It's kind of natural too. If a square is empty there's no piece object there at all. No new object has to be created and that explicit cast is gone.

  • Private or Protected access for super class variables

    What is the best practice...
    Assume there is a class hierachy like
    Person (Super class) / StaffMember/ Professor (Sub class)
    1) The best way is to keep all the instance variables of each and every class private and access the private variables of super classes through subclass constructors (calling "super()")
    Ex:-
    public class Person {
    private String empNo;
    public Person (String empNo) {
    this.empNo = empNo;
    public class Professor extends Person {
    private String ........;
    private int ...........;
    public Professor (String pEmpNo) {
    super(pEmpNo);
    OR
    2)Changing the access level of the super class variables into "protected" or "default" and access them directly within the sub classes...
    Ex:-
    public class Person {
    protected String empNo;
    public Person () {
    public class Professor extends Person {
    String ........;
    int ...........;
    public Professor (String empNo) {
    this.empNo = empNo;
    Thank you...

    i'd think that you'd be better off relaying your initial values through the super class's constructor that way you'll get cleaner code, there's a possibly of inconsistency with option 2. i.e. you can then write code in your super classes to generally handle and properly initialize the instance variables while in the case of option 2, you'll have arbitrary constructors performing arbitrary initialization procedures

  • Accessing a Sub class variable in a Super Class

    Hi ,
    Is there any easiest way to access a Subclass Variable in a Super Class.
    Class Super1{
    Class sub extends Super1
    private String substring1;
    In my application the 'substring1' values is not null .But all fields in Super1 class are null .
    How can i access the value of the Subclass Variable in Super class .
    Thanks

    This would be a way to make the superclass dependent on subclass behavior. Of course this only makes sense if getSubString() is likely to have multiple different implementations in different subclasses.
    public abstract class Super {
      public String getString() {
       return "SuperString" + getSubString();
      protected abstract String getSubString();
    public class Sub extends Super {
      private String substring;
      protected String getSubString() {
       return substring;
    }Using this just to access a variable whose contents differ from subclass to subclass is overkill. If you want each subclass to provide a different substring, create a constructor with a substring parameter in the superclass instead:public class Super {
      private String substring;
      protected Super(String substring) {
       this.substring = substring;
      public String getString() {
       return "SuperString" + substring;
    public class Sub extends Super {
      public Sub() {
       super("substring");
    }

  • 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

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

Maybe you are looking for

  • How the Partner Bank type field in Customer master is used ??

    Hi, When 2 bank accounts are maintained in the customer master. In the Bank type field ( Partner Bank type), I give X and Y for these 2 bank accounts. When an invoice is raised for this customer thru Sales order, I am not able to give this partner ba

  • Outlook 2013 VBA Event for recurring appointments

    Hello, I have VBA code that copies new Calendar entries to a secondary calendar. For recurring meetings it only copies the 1st meeting to the secondary calendar. Is there an Outlook VBA event that occurs whenever a Recurring appointment is created an

  • No sound during record with soundblaster for Vi

    I have Windows Vista and am using Audigy Advanced MB Sound Blaster Wave Studio to record music from a multi-track recording source. Wave Studio records it just fine and will play it back well, but I can't hear the music while I'm recording it, which

  • No right mouse click in Safari?

    Hi- When I right mouse click (Mighty Mouse) in Safari no popup appears. (The one that would have "Back" - "Forwar" - "Reload", etc.) In Firefox right mouse click brings up this popup as does IE. Am I missing something, can I get this to work in Safar

  • CVD Cess in J1iex

    Hi All, I have configured the new pricing procedure for CVD. I have used the Condition type JCV1. All the transactions arwe flowing smmothly, the only problenm is that the value of Cess is not flowing in J1iex. Do we have to apply any notes for the s