• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Overriding

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
In the below example, i thought the answer was "Y". But when i executed i got "X". Could someone explain this?

class A
{
public A(){};
void giveBirth(A a)
{System.out.println("X");
}
}
class B extends A
{
public B(){}
void giveBirth(B b)
{System.out.println("Y");
}
public static void main(String args[])
{
B a = newB();
A a1 = new A();
a1 = a;
a1.giveBirth(a);
}
}

Thanks,
Parasu.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello,
I think it is not a case of overriding, class B is
overloading the method giveBirth().
when you create the object of class B a = new B();
it means object a have accessibility to both version
of the method. i.e.
void giveBirth(B b) and
void giveBirth(A a).
now it creates object of class
A a1 = new A();
which is as such no use as in the next statement
a1 is started referencing to object a.
a1=a;
as a1 is of class A type , so a1 now only call the method which are defined in class A.
so wheh you call method
a1.giveBirth(a);
it will invoke the method which class B inherit from class A .
here we pass the object of class B type while method of class A
is expecting the class A object , but it is no problem it can inherently cast it to its base class type.
So it will print the "X"
Regards.
Sanjay
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sanjay,
Thanks for your explanation. But when the follwing assigment a1 = a takes place, i think a1 object will be able to access class B methods. I tried that and it working.
If thats the case, when when a1.giveBirth(a) is called it should execute the Class B's giveBirth().
Please explain me.. I am not getting this right.
Thanks,
Parasu.
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

hi parasu,
can u please explain me what u mean by saying that a1 is able to access class B methods , the program will not compile if u try to access any methods in class b which are not defined in class A through the reference a1.
I hope u iam able to make myself clear
bye
satish varanasi
 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sanjay,
I do not agree with your statement.(No offense please!!)
After a1= a statement both the references are set to the
object created by using new B(). So i think both a,a1 of them
should look at methods in the subclass object.
ex: had it been
A a1= new B();
a1.giveBirth() should have used the code in sub class
Am i right?
So i too am confused here....Experts please guide ...


 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Here is a ex :
class A {
public int i=5;
public void print("In A");
}
public class B extends A {
public int i=10; //shadows or hides the super class variable
public void print("In B"); //overrides
public static void main(String args[]) {
A a = new A();
a.print(); //prints In A
System.out.println(a.i); //prints 5
B b = new B();
b.print(); // prints In B
System.out.println(b.i); // prints 10
// now some magic time
a = b; // passing reference of sub class to super class
a.print(); //3
System.out.print(a.i) //4
// Guess whats printed
// In B
// 5
}
}
Well, when a method is called through a reference, its depends on the actual object which method is called. in //3, though the reference is of superclass A but the object it refers is of B so the subclass version of the method is called.
In case of refering a variable is concerned its different. it depends on the reference used to access the particular variable.
so even after a = b, a.i refers to i of superclass.
Anything wrong?
Thanks
Sanjeet

Originally posted by Doit:
Hi Sanjay,
I do not agree with your statement.(No offense please!!)
After a1= a statement both the references are set to the
object created by using new B(). So i think both a,a1 of them
should look at methods in the subclass object.
ex: had it been
A a1= new B();
a1.giveBirth() should have used the code in sub class
Am i right?
So i too am confused here....Experts please guide ...


 
Doit
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sanjeet, i agree with you.
Now look at the question posted by parasu. Can you please explain
that on the same lines.
- Thanks
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Warning: This is just based on my observation, those who really know the language in and out please correct/confirm. Thanks.
I think giveBirth(A a) is not overriden since the parameter list is different than giveBirth(B b), so my guess is that there are actually 2 methods (giveBirth(A) and giveBirth(B)) in class B (the 1st one is inherited).
Now here's my question. When a call to giveBirth() has been made with a reference of type A.
A a = new A();
giveBirth(a);
Which method do you think the compiler/JVM would choose? Again, my guess is that the giveBirth(A a) is chosen, hence the output "Y"
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can somebody confirm on this???
 
Sanjeet Karamchandani
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Doit,
I will try,
class A {
public A(){};
void giveBirth(A a) { System.out.println("X"); }
}
class B extends A {
public B(){}
void giveBirth(B b) {System.out.println("Y"); }
public static void main(String args[]) {
B a = newB();
A a1 = new A();
a1 = a;
a1.giveBirth(a);
}
}
In this case, the method giveBirth is overridden by subclass B. Now look at the call
a1 = a; // passing subclass to superclass
a1.giveBirth(a);
Here, though the reference is of superclass A but the actual object that it is refering is of B, agree?
Now when the compiler sees this call, it searches for the method in superclass A and finds it( Note that if it can't find it that will be a compile time error). But since the object is of subclass it searches to see whether the superclass version of he method is overridden and since its overridden the subclass version of the method is called, dynamic method lookup..OK
I hope its clear now
Thanks
Sanjeet
 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I disagree on some of the points that Sanjeet has made. Here is the way I see it:
class A
{
public A(){};
void giveBirth(A a) {
// ! NOTE: giveBirth uses a parameter of type A
{System.out.println("X");
}
}
class B extends A
{
public B(){}

void giveBirth(B b) {
// ! NOTE: giveBirth uses a parameter of type B
// therefore giveBirth is OVERLOADED
{System.out.println("Y");
}
public static void main(String args[])
{
B a = new B();
A a1 = new A();
a1 = a;
// ! Now both a and a1 "point" at an object of type B
a1.giveBirth(a);
// ! At runtime, looks in class B for a
// method with the signature giveBirth( A a )
// which it does not find in B.
// Then it looks in B's superclass, A and it finds it.
// So "X" gets printed.
}
}
Just because the arguments to giveBirth are related via a superclass/subclass relationship does not change that fact that B's version OVERRIDES A's.
 
daryl olson
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oops, I meant to say:
Just because the arguments to giveBirth are related via a superclass/subclass relationship does not change that fact that B's version OVERLOADS A's.
 
Sanjeet Karamchandani
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi daryl o,
Oops, i changed the concepts. Well, humans make mistake. U r absolutely right, its overloading and not overridding. Thanks for highlighting it.
Thanks
Sanjeet

Originally posted by daryl o:
Oops, I meant to say:
Just because the arguments to giveBirth are related via a superclass/subclass relationship does not change that fact that B's version OVERLOADS A's.


 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Daryl o,
I have a question in your explanation...
when a1.giveBirth(a) is called, since a1, and a are refering to the same object which is of type B, then it should look for a method of the following signature
giveBirth( B a ) and not to giveBirth( A a ). I am still not convinced with so many diff reply's..
pls clarify me..
Baskaran.
 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi parsu,
it was good question ,we will parse the whole prg slowly
in main method a1=a;
a1 is an object of super class A
a is object of class B which inherits A
in a1=a;
since a1 is a super class object it will not know what subclass method are and it will just be refering B.So naturally if any method invoked using object a1, it will search for the corresponding method in class A if found it will execute else it gives a compile error
hope i am clear
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I tried these to explain the output....
1. Masked out (//) the a1 = a; command and executed the programme.
2. In the part a1.giveBirth(a); tried these and executed the programme each time:
a.giveBirth(a1);
a.giveBirth(a);
a1.giveBirth(a1);
In ALL these cases I got X as output...
In my opinion even though giveBirth() is overloaded the sub-class's giveBirth() is never called because the argument
that is passed (a1,a)always matches the parent's giveBirth() argument.
Saptadeep,
Delhi, India.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Here the method giveBirth() is not atall overridden because parameter types are totally different, no matter if the types are parent or son. They are totally different.
now a1 is a parent object holder and it points to a son object.
When you call a1.giveBirth() method, if you expect the son's method be invoked, the son should have overridden this method, again that means signature of the overriding and overridden methods are exactly the same. In this case no overriding has happened. So java picks the method from parent class and with difficulty it convert son's object reference to parent's object reference and execute it which results in the printing of X.
biju
 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
I had read the question and the answers confused me more. Here is a program in which I tried it and the output.
class class1{
void showTxt(class1 cl1){
System.out.println("in class1 ");
}
}
class class2 extends class1{
void showTxt(class2 cl2){
System.out.println("in class2");
}
}
public class testClass{
public static void main(String[] args) {
int j = 5;
class1 obj1 = new class1();
class2 obj2 = new class2();
obj1.showTxt(obj1);
obj1.showTxt(obj2);
obj2.showTxt(obj2);
obj2.showTxt(obj1);
obj1 = obj2;
obj1.showTxt(obj2);
}
}
and the output is :
in class1
in class1
in class2
in class1
in class1
Now I can understand the first four lines. but it is the last line that has me foxed and it essentially is the question first asked.
My question is since after assignment obj1 = obj2 it means that obj1 essentially points to an object of class2 and hence the methods invoked should be the one which belongs to class2 and also the parameter supplied in the last call to showTxt is with an object of class2 so I would expect the method in class2 to be implemented.
Am I missing something here?
thanks for your help
 
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi anshul
excellent problem u have presented
let me work on it and i will get back to u
as for the first post
THERE IS NO OVERRIDING THERE
IT WAS OVERLOADING
hey guys the problem presented by anshul is quiet interesting
please put in ur feedback
 
sona gold
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what i assume anshul here again is
overloading
now in the last statement also
since it is overloading and not overriding, and obj2 paramaeter class 2 automatically fits into class 1 the output is from the first method
i would still appreciate if someone experienced interferred into this
thx
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Anshul (and everybody else)
in my view 3 general rules apply her:
1. A reference can only point to objects either
a. has the same type as the reference self
b. is a subtype of the reference's type
2. With a reference can you only access fields and methods which
a. are declared as the same type as the reference (class or
interface)
b. are declared as a super-type to the type of the reference
3. No matter what the type of the reference is; it is the method
closest to the object's own type, that get to be executed.
in relation to your (fun) program I see a possible explanaition as this:
obj1 ia reference of type class1, that never changes.
when obj1=obj is executed, obj1 points to an object of type class2 ( a subtype.)
When obj1.showTxt(obj2); gets called the following happens:
1. the reference obj1 of type class1 does not know of a method called void showTxt(class2), so the argument obj2 of type class2 get upcastet to type class1. So the method showTxt(class1) in class1 gets executed, printing "in class1".
I relation to the 3 rule, I think no. 2 is the one to focus on here.
I'am no expert, I have just been fighting this very problem in a school assignment recently.
I hope I didnt add to the confusion.
Regards
Christian
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Obviously the answer has already been given correctly, so I will just point out that instances of class1 have only 1 method. That is the showTxt() method that accepts a parameter of class1.
Instances of class2 have 2 (overloaded) methods. showTxt that accepts class1 inherited from the super class, and showTxt that accepts class2 as added by the subclass.
Whichever parameter you pass will determine which method gets invoked.
 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi everybody,
a1=a;
This line itself explains that at runtime the interpreter knows that a1 is still type Object A so its method (that prints option 'X') is invoked, but at the same time if you print a1.somevariable then it should print Class B's variable bexoz it has been casted as type a which is object of Class B.
I hope its clear.
Jyotsna

Originally posted by parasu:
Hi all,
In the below example, i thought the answer was "Y". But when i executed i got "X". Could someone explain this?

class A
{
public A(){};
void giveBirth(A a)
{System.out.println("X");
}
}
class B extends A
{
public B(){}
void giveBirth(B b)
{System.out.println("Y");
}
public static void main(String args[])
{
B a = newB();
A a1 = new A();
a1 = a;
a1.giveBirth(a);
}
}

Thanks,
Parasu.


 
reply
    Bookmark Topic Watch Topic
  • New Topic