Friday, January 17, 2014

Why this code does not compile successfully?

//JustAnInterface.java

public interface JustAnInterface {
     void testIt();
}

//JustAClass.java
public class JustAClass implements JustAnInterface{
    void testIt(String msg){
        System.out.println(msg);
    }

    void testIt(){
       System.out.println("I am from an Interface");
    }
}

If you know the reason : type in comments

Wait for my answer : I'll post it as a comment

By Nancy
@ 6:10 am 1/18/2014


5 comments:

  1. visibility of the inherited method from JustAninterface.JustAnInterface in not accessiable
    for method void testIt()

    ReplyDelete
  2. The interface method testIt() is implicitly public, but the implementation in JustAClass is package-private, and the compiler doesn't allow a subtype to reduce the visibility of a virtual method.

    ReplyDelete
  3. Hi, Interface methods are Public abstract by default.

    Like:- Your interface

    public interface JustAnInterface {
    public abstract void testIt();
    }

    But in your class your method is having default access modifier which is having less visibility than public method declaried in interface so your class throws compile time error . Your class should be like.

    //JustAClass.java
    public class JustAClass implements JustAnInterface{
    void testIt(String msg){
    System.out.println(msg);
    }

    public void testIt(){
    System.out.println("I am from an Interface");
    }
    }

    ReplyDelete
  4. It is good practice to have an access specifiers and qualifiers to the interface method declarations.

    ReplyDelete
  5. Awesome. Methods declared in an interface by default are public and abstract. And when a class implements an interface it can broden the scope but cannot narrow it. Default access in class for any method or attribute is package level access. Hence in class public method cannot be overridden as package level. A method from interface MUST be always public in class... :) enjoy Java :)

    ReplyDelete