• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inheritance question

 
adam Lui
Ranch Hand
Posts: 186
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

in class Test, how can we possibly to use superclass's aMethod?
 
veda vyas sista
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 186
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 69
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic