Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Accessor Types Public and Private

Question 1

Given :

public class Hello{
private int i = j;
private int j = 10;
public static void main(String args[]) {
System.out.println((new Hello()).i); }
}

Choose

1. Compiler Error Complaining about access restriction of private variables of Hello.
2. Compiler error complaining about forward referencing.
3. No error - The output is 0;
4. No error - The output is 10;

Answer is 2. It is because i is a private variable of Hello. Hence it cannot be accessed directly.

Question 2


Given :

public class Hello {
private int i = giveJ();
private int j = 10;
private int giveJ()
{ return j;
}
public static void main(String args[])
{ System.out.println((new Hello()).i);
}
}

Choose :
1. Compiler error complaining about access restriction of private variables of Hello.
2. Compiler error complaining about forward referencing. .
3. No Compilation error - The output is 0;
4. No Compilation error - The output is 10;


Answer 2 is correct. We cannot assign a value to instance varaible by calling the method.


This post first appeared on SCJP Tutorial -1.5 Tips And Tricks, please read the originial post: here

Share the post

Accessor Types Public and Private

×

Subscribe to Scjp Tutorial -1.5 Tips And Tricks

Get updates delivered right to your inbox!

Thank you for your subscription

×