110.
In the above code, Lines 1 and 3 will cause a compilation error.
All the fields declared in an interface
need to be public static and
final. If the public static and final keywords are not specified, the
field is implicitly made public static final. Line 1
explicitly
specifies the private keyword and so causes a compilation
error. Line 2 does not
have the public static final
keywords specified. However, this does not cause a compilation
error, Java implicitly
makes the field public, static and
final. Line 3 specifies the public and final keyword but
does not initialize the field. A final field needs to be initialized.
So, Line 3 causes a compilation error as well. Line 4 specifies the
public and static keywords and initializes the field. It does not
specify the final keyword. However, this again does not cause a
compilation error, the field is implicitly treated as final.
Is the code snippet below valid? Explain.
public abstract class MyAbstractClass {
private abstract void doSomething();
}
Answer:
The above code is invalid and causes
a compilation error for the
doSomething method. This is because the doSomething ()
method is both abstract and private. An abstract method
cannot be made private. A private method
is not accessible
in the sub–class. An abstract method needs to be accessible
in the sub–class in order for the sub–class
to provide
an implementation for the method. A sub–class will not be able to
provide an implementation for an abstract private method.