This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "inheritance question" Watch "inheritance question" New topic

inheritance question

adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186

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

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();

Also name the file as 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();
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?
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)

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



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