Share on Google+Share on Google+

SCJP Module-3 Question-3

Advertisement
The given sample program test your knowledge of Inner and Outer class in Java and their access restrictions.

Given a sample code:

class OuterClass {
private int x = 2;

OuterClass() {
outerMethod();
}

public static class InnerClass {
private int x = 1;

public void innerMethod() {
System.out.println("inner x is " + x);
}
}

public void outerMethod() {
System.out.println("outer x is " + x);
}
}

public class Test {
public static void main(String args[]) {
OuterClass o = new OuterClass();
o.outerMethod();
OuterClass.InnerClass i = new OuterClass.InnerClass();
i.innerMethod();
}
}

What will be the result of above code ?

(1)   outer x is 2
        outer x is 2
        inner x is 1

(2)    outer x is 1
         inner x is 2
         inner x is 2

(3)    inner x is 2
        outer x is 2
         inner x is 1

(4)    inner x is 2
        outer x is 2
        outer x is 1

Answer:

(1)

Advertisements

Posted on: July 9, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.