CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Classes

  1. #1
    Join Date
    Apr 1999
    Location
    Houston,Tx
    Posts
    9

    Classes

    Hi,

    I need an urgent explanation for the following code.

    class Super
    { int index = 5;
    public void printVal()
    { System.out.println( "Super" );
    }
    }
    class Sub extends Super
    { int index = 2;
    public void printVal()
    { System.out.println( "Sub" );
    }
    }
    public class Runner
    { public static void main( String argv[] )
    { Super sup = new Sub();
    System.out.print( sup.index + "," );
    sup.printVal();
    }
    }
    Ans: 5,sub

    Thanks,
    Deepa


  2. #2
    Join Date
    Apr 1999
    Location
    Bangalore,India
    Posts
    43

    Re: Classes

    Hi,

    Variables in java are statically linked to the object and accessed depending upon the type
    of the object.But the methods are accessed by the reference of the object.
    So when u say sup.printVal(), the printVal() method of Sub class is called
    because the object sup of type Super carries the reference of its sub class Sub.
    As instance methods are accessed by reference, the method printVal() of Sub class.
    So u r getting the output as "Sub".

    When u are trying to print the value of index using sub.index, the object type is checked
    and the index value of that object type is output. So only u get "5". If u want to
    get%

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured