Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance

 
Ana P
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at this example...
class Super{
public Super() //1
{
a();
}
void a() //1
{
method();
}
void method() //3
{
System.out.println("1");
}
}
public class Subclass1 extends Super{
public Subclass1()//4
{
a();
}
public void method() //5
{
System.out.println("2");
}
public static void main(String []args) {
Super c = new Subclass1(); // 4 - 1 - 3
}
}

The output of this prog is 2 2
I thought it should be 1 2
how this works?
Super c = new Subclass1(); // 4 - 1 - 3
after this line control will go to super class constructor. and then method a() at 1 and then call to method at 3. but it does not work that way
pls explain...
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to Programmer Certification Study
Please continue the discussion there. Thanks!
Also, "Ana P" Can you please adjust your displayed name to meet the JavaRanch Naming Policy. You can change it here.
Welcome to the JavaRanch!
[ May 08, 2002: Message edited by: Jessica Sant ]
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're very close, Ana. The difference is that the method "method" is overridden in the class Subclass1. Therefore, when method() is invoked in Super.a(), dynamic binding is used to determine which method to invoke. As the run-time object is of type Subclass1, the method "method()" from Subclass1 is invoked, rather than the method "method()" from Super.
I hope that helps,
Corey
In addition, you can check out this thread which covers this topic.
[ May 08, 2002: Message edited by: Corey McGlone ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic