Connecting Tech Pros Worldwide Forums | Help | Site Map

Inheritance Doubt

Newbie
 
Join Date: Oct 2006
Posts: 21
#1: Oct 10 '07
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.println("base.f()");
g();
}
public void g(){
System.out.println("base.g()");
}
}

class derived extends base {
public void g(){
System.out.println("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().

Newbie
 
Join Date: Oct 2006
Posts: 21
#2: Oct 10 '07

re: Inheritance Doubt


I am sorry as i recalled now that all methods in java defaults to virtual. In C++, it needs to be done explicitly.
dmjpro's Avatar
Lives Here
 
Join Date: Jan 2007
Location: India (West-Bengal)
Posts: 2,451
#3: Oct 10 '07

re: Inheritance Doubt


Quote:

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.println("base.f()");
g();
}
public void g(){
System.out.println("base.g()");
}
}

class derived extends base {
public void g(){
System.out.println("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
Reply


Similar Java bytes