aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes super class Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "super class" Watch "super class" New topic
Author

super class

Arivu Selvi
Greenhorn

Joined: Dec 06, 2006
Posts: 2
Can anybody explain how the output here is 22?

class Base {
int i;
Base() { add(1); }
void add(int v) { i += v; }
void print() { System.out.println(i); }
}

class Extension extends Base {
Extension() { add(2); }
void add(int v) { i += v*2; }
}

public class Qd073 {
public static void main(String[] args) {
bogo(new Extension());
}
static void bogo(Base b) {
b.add(8);
b.print();
}
}
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 8795

This question is explained in the Khalid Mughal's book itself.


SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
Vishal K Patel
Ranch Hand

Joined: Oct 20, 2006
Posts: 43
Here, when the is called, automatically super constructor will be called.

Form the super constructor, add method is called with argument 1. but the method from child class will be executed at run time as the original object is from child class.

This is the good example of polymorphisms.

I think it's enough to get the reason.....
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: super class
 
Similar Threads
Constructor Problem
program output
Another question
Constructors & methods
How to read this program?