Monday, August 16, 2010

Interface related questions

1:
public interface AQuestion
{
     public abstract void someMethod() throws Exception;
}


class AQuestionImpl implements AQuestion
{
    public void someMethod()
    {
        System.out.println("someMethod");
    }
}

Q: Will the code compile? Why did the code compile successfully when implementation method is not declared abstract?
The above code will compile as all methods of interface are public and abstract. And implementation method should implement the method.

Q: Why did code compile when implementation method did not throw Exception?
A:  Exception is not a checked exception so it is not necessary to specify throws clause for Exception.

                                                                                                                                                                                     

Can an interface be private or protected?

private interface PrivateInf
{
    public abstract void someMethod() throws Exception;
}

class AQuestionImpl implements PrivateInf
{
    public void someMethod()
    {
        System.out.println("someMethod");
    }
}

Output: Compile error
modifier private not allowed here
private interface PrivateInf
        ^
1 error

                                                                                                                                                                                      


public interface AQuestion
{
     void someMethod() throws Exception;
}

class AQuestionImpl implements AQuestion
{
    void someMethod()
    {
        System.out.println("someMethod");
    }

}

Output: Compile error

attempting to assign weaker access privileges; was public
    void someMethod()
         ^
1 error

Reason: the method declared in interface is implicitly public. So the implementation must be declared public.

________________________________________________________________________________________

public interface AQuestion
{
     void someMethod() throws Exception;
}

class AQuestionImpl implements AQuestion
{
    public final void someMethod()
    {
        System.out.println("someMethod");
    }

}

Output: It compiles, the methods declared in interface are implicitly public and abstract. However its implementation can be final. It means that the implemented method cannot be overridden.

No comments:

Post a Comment