Inheritance Doubt

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vinothg
    New Member
    • Oct 2006
    • 21

    #1

    Inheritance Doubt

    Hi ,

    I am migrating slowly from c++ to java. The output of the following program differs from c++ in java. It should be really easy for any java programmer to explain. Just an hint could help me to understand.


    class base {
    public void f(){
    System.out.prin tln("base.f()") ;
    g();
    }
    public void g(){
    System.out.prin tln("base.g()") ;
    }
    }

    class derived extends base {
    public void g(){
    System.out.prin tln("derived.g( )");
    }
    }

    public class bade{
    public static void main(String[] args){
    base p = new derived();
    p.f();
    }

    o/p in java -> base.f(), derived.g()
    o/p in c++ -> base.f(),base.g ().
  • vinothg
    New Member
    • Oct 2006
    • 21

    #2
    I am sorry as i recalled now that all methods in java defaults to virtual. In C++, it needs to be done explicitly.

    Comment

    • dmjpro
      Top Contributor
      • Jan 2007
      • 2476

      #3
      Originally posted by vinothg
      Hi ,

      I am migrating slowly from c++ to java. The output of the following program differs from c++ in java. It should be really easy for any java programmer to explain. Just an hint could help me to understand.


      class base {
      public void f(){
      System.out.prin tln("base.f()") ;
      g();
      }
      public void g(){
      System.out.prin tln("base.g()") ;
      }
      }

      class derived extends base {
      public void g(){
      System.out.prin tln("derived.g( )");
      }
      }

      public class bade{
      public static void main(String[] args){
      base p = new derived();
      p.f();
      }

      o/p in java -> base.f(), derived.g()
      o/p in c++ -> base.f(),base.g ().
      Yes buddy .............. at the beginning you are trying to understand the base concept of Java.
      Really happy to see that :-)
      Actually Java resolves these during runtime.
      Have a look at "Class","Method " and it's relevant classes.
      Then you will understand that by yourself.

      Debasis Jana

      Comment

      Working...