Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access instance variables from default method in inner interface

Given that we now have default methods on an interface in Java 8, is there any way that we can access instance methods from a parent class in a inner (non static) interface, for example something like this:

public class App {

    int appConst = 3;

    public interface MyInstanceInterface {

        default int myAppConst() {
            return appConst;
        }
    }
}

My interface is not static and therefore it should be able to access appConst in the App.this context.

This code fails with the following compile error:

error: non-static variable appConst cannot be referenced from a static context

Why?

like image 923
Boris the Spider Avatar asked Sep 08 '14 10:09

Boris the Spider


People also ask

Why can't we use instance variables inside the default method?

Because variables used inside a default method of an interface have access only to the variables defined inside the interface. Remember variables defined inside an interface are public,static and final and they must be initialized. within calling class.. You can only access instance variable inside "Bar" class by overriding default method.

How to access an instance variable from a static method?

Therefore, accessing it directly from a static method, which is not tied to any specific instance doesn't make sense. Therefore, to access an instance variable, we must have an instance of the class from which we access the instance variable.

What are interface variables in Java?

Learn Interface variables in Java with example and Uses. You know that an interface can contains methods in java, similarly, an interface can contains variables like int, float and string too. In an interface, variables are static and final by default. All variables in an interface in java should have only public access modifier.

How to access instance variable inside Bar class in Java?

You can only access instance variable inside "Bar" class by overriding default method. Like so, public class Bar implements Foo { int BAZ = 10; @Override public int getBazModified () { return BAZ * 2; } }


1 Answers

The reason for this is JLS §8.5.1:

A member interface is implicitly static (§9.1.1). It is permitted for the declaration of a member interface to redundantly specify the static modifier.

An inner interface can never be non-static. The declaration:

public class App {

    ...      

    public interface MyInterface {

        ...

    }
}

Is exactly equivalent to:

public class App {

    ...      

    public static interface MyInterface {

        ...

    }
}

N.B: this has always been the case, and merely remains unchanged in Java 8.

like image 130
Boris the Spider Avatar answered Oct 17 '22 13:10

Boris the Spider