Pass by value or reference
HI. I am a C++ programmer mingrating to Java
I have this query..Does Java support pass by value or pass by reference.
Following code suggests that Java supports Pass by reference as it calls the "callme " function from the derieved
class. But then it calls the constructor of the base class also which suggests that it makes a copy of base class...It
means its pass by value..
Please help
class Base {
Base(){
System.out.println("I am in base class constructor ");
}
void callme(){
System.out.println("I am in base class");
}
}
class Derieved extends Base {
void callme(){
System.out.println("I am in derieved class");
}
}
class dispatch {
public static void main(String args[]) {
Derieved dd = new Derieved() ;
fff(dd);
}
}
static void fff(Base bb){
bb.callme();
}
}
OUTPUT is
I am in base class constuctor
I am in base derieved class
Re: Pass by value or reference
Java (almost) always uses pass by reference. The only time it uses pass by
value is for int, boolean, char etc. Note that in Java all access to an object
is through its reference.
The first line of output you get is when the Derived class is constructed. As in
C++, the subclass construction continues only after the base class portion gets
constructed.
The second line of output of course is from the callme() of the Derived class.
Re: Pass by value or reference
Mr. Manoj
the out put is
I am in base class constructor
"I am in base class"
b'coz u r calling the method of the base class using it's object obviously the result is as above and the constructor is calls by default when ever u create ad nobject of the class
vinay kumar s.v