0
 interface TestInterface
 {
    public static void square(int a)
    {
        System.out.println("Square is "+a*a);
    }

    public static  void show()
    {
        System.out.println("Default Method Executed");
    }

 }
class TestClass implements TestInterface
{
    public void square(int a)
    {
        System.out.println(a*a);
    }

    public void show()
    {
        System.out.println("Overridden Method");
    }
    public static void main(String args[])
    {
        TestClass d=new TestClass();
        d.square(4);
        TestInterface.square(4);
        TestInterface.show();
        d.show();
    }
}

I have a doubt in my code. I learnt that static methods cannot be overridden in JAVA, but it seems to be working fine here. When i give both default and static keywords together, like this

interface TestInterface
   {
        default static void square(int a)
        {
            System.out.println("Square is "+a*a);
        }

        public static  void show()
        {
            System.out.println("Default Method Executed");
        }

    }

An error crops up as follows: illegal combination of modifiers: static and default

What is the reason for JAVA treating this as an error?

  • 4
    The static methods are **shadowed** not overridden. – Code-Apprentice Jul 29 '17 at 06:02
  • Thank you for the explanation. @Code-Apprentice, what do you mean by the words "Shadowed and not overridden"? Does the compiler treat the static and non static methods as two completely different entities? Even if they have same signature? –  Jul 29 '17 at 06:24
  • Try that prior research thing the next time. – GhostCat Jul 29 '17 at 06:45

2 Answers2

3

A static method is meant to be called without an instance of the class/interface concerned. Usually they are meant to be utility methods.

A default method is meant to be called on an instance of the interface concerned. All implementations of this interface will have this method definition, unless it is overridden.

The reason these two terms are not allowed together is simply because they contradict each other: default requires an object, static requires no object.

Joe C
  • 15,324
  • 8
  • 38
  • 50
0

TestClass.show() and TestClass.square() are not static and therefore do not override the static methods in the interface. They are member methods and require an object to call them. On the other hand, the methods with the same name in the interface are static and so you can call them with the interface name or class name without an object.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268