File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object Reference

 
Anchul
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got your point.Thanks a ton. I apprecite your time.
 
Rajesh Gupta
Greenhorn
Posts: 20
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried your program but I'm getting:
Exception in thread "main" NoSuchMethodError:main
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic