Java Programming - Declarations and Access Control
Exercise : Declarations and Access Control - Finding the output
- Declarations and Access Control - General Questions
- Declarations and Access Control - Finding the output
- Declarations and Access Control - Pointing out the correct statements
1.
What will be the output of the program?
class A
{
final public int GetResult(int a, int b) { return 0; }
}
class B extends A
{
public int GetResult(int a, int b) {return 1; }
}
public class Test
{
public static void main(String args[])
{
B b = new B();
System.out.println("x = " + b.GetResult(0, 1));
}
}
Answer: Option
Explanation:
The code doesn't compile because the method GetResult() in class A is final and so cannot be overridden.
2.
What will be the output of the program?
public class Test
{
public static void main(String args[])
{
class Foo
{
public int i = 3;
}
Object o = (Object)new Foo();
Foo foo = (Foo)o;
System.out.println("i = " + foo.i);
}
}
3.
What will be the output of the program?
public class A
{
void A() /* Line 3 */
{
System.out.println("Class A");
}
public static void main(String[] args)
{
new A();
}
}
Answer: Option
Explanation:
Option D is correct. The specification at line 3 is for a method and not a constructor and this method is never called therefore there is no output. The constructor that is called is the default constructor.
4.
What will be the output of the program?
class Super
{
public int i = 0;
public Super(String text) /* Line 4 */
{
i = 1;
}
}
class Sub extends Super
{
public Sub(String text)
{
i = 2;
}
public static void main(String args[])
{
Sub sub = new Sub("Hello");
System.out.println(sub.i);
}
}
Answer: Option
Explanation:
A default no-args constructor is not created because there is a constructor supplied that has an argument, line 4. Therefore the sub-class constructor must explicitly make a call to the super class constructor:
public Sub(String text)
{
super(text); // this must be the first line constructor
i = 2;
}
5.
What will be the output of the program?
public class Test
{
public int aMethod()
{
static int i = 0;
i++;
return i;
}
public static void main(String args[])
{
Test test = new Test();
test.aMethod();
int j = test.aMethod();
System.out.println(j);
}
}
Answer: Option
Explanation:
Compilation failed because static was an illegal start of expression - method variables do not have a modifier (they are always considered local).
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers