Questions for: Declarations And Access Control
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);
}
}
Compilation failed because static was an illegal start of expression - method variables do not have a modifier (they are always considered local).
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);
}
}
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;
}
Discuss About this Question.
public class A
{
void A() /* Line 3 */
{
System.out.println("Class A");
}
public static void main(String[] args)
{
new A();
}
}
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.
Discuss About this Question.
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);
}
}
Discuss About this Question.
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));
}
}
The code doesn't compile because the method GetResult() in class A is final and so cannot be overridden.
Discuss About this Question.
Discuss About this Question.