File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Object Reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Object Reference" Watch "Object Reference" New topic
Author

Object Reference

Anchul
Greenhorn

Joined: May 30, 2000
Posts: 9
Considering the following code can anyone explain me in detail that why does b.i print '99' and b.amethod() calls the subclass amethod. What goes behind the scene ? :
class base{
int i=99;
void amethod()
{
System.out.println("Base.amethod");
}
}
class subclass extends base
{
int i=1;
public static void main(String argv[])
{
base b=new subclass();
System.out.println(b.i);
b.amethod();
}
void amethod()
{System.out.println("Base.amethod");
}
}
Thanks a Lot
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hi,
u have created a object of a subclass with a reference to that of the superclass. Invoking a method of that is overridden invokes the method of the subclass not the superclass. however this is not the case of variables or fields even though they are hidden in the subclass. such a reference will still have its fields rather than that of the subclass.
class base{
int i=99;
void amethod()
{
System.out.println("Base.amethod");
}
}
class subclass extends base
{
int i=1;
public static void main(String argv[])
{
base b=new subclass();
System.out.println(b.i);
b.amethod();
}
void amethod()
{System.out.println("sub.amethod");
}
}
this prints out 99 and sub.amethod.
Anchul
Greenhorn

Joined: May 30, 2000
Posts: 9
I got your point.Thanks a ton. I apprecite your time.
Rajesh Gupta
Greenhorn

Joined: Jun 21, 2000
Posts: 20
I tried your program but I'm getting:
Exception in thread "main" NoSuchMethodError:main
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hi Rajesh,
This is because u r saying
java base
this will not work
first save the file as subclass.java or base.java
invoke java compiler with
javac subclass.java // if u saved the java file as subclass.java
or javac base.java // if u have saved the file as base.java
then say
java subclass
this works
this is because when u say java base the JVM searches this file
for the main method and does not find it.
however when u say java subclass it finds the main method and invokes it.
regds
Rahul

[This message has been edited by rahul_mkar (edited June 27, 2000).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Object Reference
 
Similar Threads
Method from constructor
Doubt in Mock Question
why is the result?
Help with this one from Markus Green's mock exam
Why superclass reference invokes subclass method