Declaration And Access Control - Study Mode

[#36] Which keyword is used to explicitly specify that a method should be overridden in a subclass?
Correct Answer

(A) override

[#37] Choose all the lines which if inserted independently instead of "//insert code here" will allow the following code to compile: public class Test{
public static void main(String args[]){
add()
add(1)
add(1, 2)
}
// insert code here
}
Correct Answer

void add(Integer... args){}

Explanation

Solution: var-args = variable number of arguments = 0 or many void add(Integer... args){} is correct IF made "static" as it's called from a static context: main(). Var-args can be of both object(eg Integer) and primitive(eg int) types. static void add(int... args, int y){} is correct IF its parameters' order is reversed. If a method has both var-arg(0 or MAX 1) + non-var-args(0 or more) parameters then the var-arg parameter MUST come LAST! static void add(int args...){} : "..." must come after the type of the var-arg parameter, not after its name static void add(int[]... args){} : for this to be a correct declaration then add() should have been called something like this: "add(arr)
" or "add(arr, arr)
" where "arr" could be defined as "int[] arr = new int[5]
" static void add(int...args){} is a valid way to define var-args (there is no need to have any space between "..." and the type and name of the var-arg param)

[#38] What is the result of compiling and running the following code? class Base{
private Base(){
System.out.print("Base")
}
}
public class test extends Base{
public test(){
System.out.print("Derived")
}
public static void main(String[] args){
new test()
}
}
Correct Answer

(D) Compilation Error

Explanation

Solution: Implicit super constructor Base is not visible, must explicitly invoke another constructor.

[#39] What is the result of compiling and running the following code? public class Tester{
static int x = 4
public Tester(){
System.out.print(this.x)
// line 1
Tester()
}
public static void Tester(){ // line 2
System.out.print(this.x)
// line 3
}
public static void main(String... args){ // line 4
new Tester()
}
}
Correct Answer

(C) Compile error at line 3 (static methods can't invoke this)

Explanation

Solution: static methods can't invoke 'this'.

[#40] What is the result of compiling and running the following code? public class Tester{
static int x = 4
int y = 9
public Tester(){
System.out.print(this.x)
// line 1
printVariables()
}
public static void printVariables(){
System.out.print(x)
// line 2
System.out.print(y)
// line 3
}
public static void main(String... args) { // line 4
new Tester()
}
}
Correct Answer

(B) Compile error at line 3 (static methods can't make reference to non-static variables)

Explanation

Solution: static methods cannot make references to non-static variables.