aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding" Watch "Overriding" New topic
Author

Overriding

parasu
Greenhorn

Joined: Apr 15, 2002
Posts: 1
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.
Sanjay Tiwari
Greenhorn

Joined: Aug 11, 2000
Posts: 1
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
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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.
Satish Varanasi
Ranch Hand

Joined: Aug 13, 2000
Posts: 47

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
Doit
Ranch Hand

Joined: Aug 03, 2000
Posts: 169
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 ...


Sanjeet Karamchandani
Ranch Hand

Joined: Jul 29, 2000
Posts: 30
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

Joined: Aug 03, 2000
Posts: 169
Sanjeet, i agree with you.
Now look at the question posted by parasu. Can you please explain
that on the same lines.
- Thanks
Ken Lai
Ranch Hand

Joined: Aug 06, 2000
Posts: 30
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

Joined: Nov 22, 2008
Posts: 18944
Can somebody confirm on this???
Sanjeet Karamchandani
Ranch Hand

Joined: Jul 29, 2000
Posts: 30
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
daryl olson
Ranch Hand

Joined: Aug 15, 2000
Posts: 36
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

Joined: Aug 15, 2000
Posts: 36
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

Joined: Jul 29, 2000
Posts: 30
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.

Baskaran Subramani
Ranch Hand

Joined: Jul 30, 2000
Posts: 38
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.
thejus/mahesh
Greenhorn

Joined: Aug 21, 2000
Posts: 19
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

Joined: Nov 22, 2008
Posts: 18944
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.
Biju Narayanan
Greenhorn

Joined: Aug 25, 2000
Posts: 4
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
Anshul Manisha
Ranch Hand

Joined: Apr 17, 2001
Posts: 74
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

AM<BR> <A HREF="mailto:anshulmohan@rediffmail.com" rel="nofollow">anshulmohan@rediffmail.com</A>
sona gold
Ranch Hand

Joined: Feb 14, 2001
Posts: 234
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<br />SCJP
sona gold
Ranch Hand

Joined: Feb 14, 2001
Posts: 234
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
Chris IT-C
Greenhorn

Joined: Jun 03, 2001
Posts: 3
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
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
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.


"JavaRanch, where the deer and the Certified play" - David O'Meara
Jyotsna Umesh
Ranch Hand

Joined: May 09, 2001
Posts: 94
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.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overriding
 
Similar Threads
Inner Class basic dought
Inheritance
abstract class instantiation
Need explanations of inheritance
How to find Object type.