my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes inheritance question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "inheritance question" Watch "inheritance question" New topic
Author

inheritance question

adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186

in class Test, how can we possibly to use superclass's aMethod?


boolean b = true;<br />System.out.println ("I believe in Java.<br />Java will make my dream come " + b);
veda vyas sista
Greenhorn

Joined: Sep 21, 2007
Posts: 10
Simply you create object of SuperClass in Test class and call that method using that object or instance like
SuperClass obj = new SuperClass();
obj.aMethod();


Also name the file as Test.java since the main method is in Test class



class SuperClass {
SuperClass() {
System.out.print(" I was in Super Class." );
}
public void aMethod (int i)
{ //line 1, superclass's aMethod
System.out.print (" The value of i is " + i );
}
}
class SubClass extends SuperClass
{
public void aMethod(int j)
{
System.out.print (" The value of j is " + j );
}
}
class Test {
public static void main(String args[])
{
SuperClass obj = new SuperClass();
obj.aMethod(5);
}
}
adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
thanks for your reply

if i was to make a reference variable of type subclass, is it possible to use aMethod in the superclass?
cheers.
Robert Elbourn
Ranch Hand

Joined: Oct 15, 2007
Posts: 69
I think not....

You could cast the subclass as a superclass

say Y (subClass) extends X (SuperClass)
eg.

superClass = (X) subClass;

but at runtime the JVM will know that subClass has its own method and calls that not the superclass one.

The only way to call the super method (that I can think of) is to put a call to super inside the method declaration the subclass

like

super.aMethod(j);

hope this isn't too confusing, and if i am wrong would love to be corrected!!!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: inheritance question
 
Similar Threads
static variable?
Need help explaining some results
static in a method
private methods
Help me