Quiz4_92932.pdf

April 7, 2014
Java Quiz 4
Sharif University of Technology
Name :
Student Id :
1.
What is used instead of a destructor in Java?
2.
Is it a good practice to define all variables private and use getters and setters? Why or why not?
3. Which of the following statements accurately describe the use of access modifiers
(private,public,protected) within a class definition? (choose one)
A.They can be applied to both data & methods
B.They must precede a class's data variables or methods
C.They can follow a class's data variables or methods
D.They can appear in any order
E.They must be applied to data variables first and then to methods
1
4. What is the output of the following code?
public class Test {
private int a = 5;
{
a++;
b++;
}
private static int b = 10;
static
{
b++;
}
private Test()
{
a++;
b++;
}
public static void main(String[] args)
{
System.out.println(Test.b);
Test test = new Test();
System.out.println(Test.b);
System.out.println(test.a);
}
}
5. (Bonus Question) Explain what the following code does:
public class Singleton
{
private static Singleton instance = new Singleton();
private int a;
private Singleton ()
{
a = 5;
}
public static Singleton getInstance()
{
return instance;
}
}
2