This question already has answers here:
Cannot make a static reference to the non-static field memberVariable with private variable
(3 answers)
Closed 3 years ago.
Error: java: non-static method a() cannot be referenced from a static context
I get this error on the following code.
enum ENUM
{
A()
{
{
a();
}
}
,
;
private void a()
{}
}
I expect this to compile, but it doesn't.
Changing the access level modifier private from method a() to any other lets the code compile.
What may prevent this code from compiling?
You get this compile error because enum constants like A here are implicitly static. That's the reason we can use the enum constants like eg: ENUM.A in any other class.
Thus we cannot call a non-static method from a static context. Refer this documentation for more details on enums
The error message is misleading. It's not limited to enums, or to initializer blocks or anything. The problem is simply that an anonymous inner class cannot access private methods from its enclosing class.
private states that sub-classes should not have visibility, and an anonymous inner class is a sub-class so it makes logical sense.
You can observe the same problem with this example:
class Foo {
public static void main(String[] args) {
Foo foo = new Foo(){
void bar() {
a();
}
};
}
private void a(){ /* do nothing */ }
}
Related
This question already has answers here:
no enclosing instance of type... in scope
(2 answers)
Closed 5 years ago.
My code is as following :-
A class T can extend ClassO.Four. Four is a static class inside ClassO but cannot extend ClassO.Two Two is an inner class inside ClassO. I am getting error
No enclosing instance of type ClassO is available due to some intermediate constructor invocation
What is the reason of difference in behaviour?
class ClassO
{
interface inner
{
void msg();
}
class Two implements inner
{
public void msg()
{
System.out.println("Class Two");
}
}
static class Four
{
public void msg()
{
System.out.println("Class Four");
}
}
public void m()
{
}
}
class T extends ClassO.Two **// can extend ClassO.Four but not ClassO.Three**
{
public void msg()
{
System.out.println("Class Two");
}
}
Recall that a static inner class is a "normal" class with the name nested inside its owner class, and additional access privileges to private static members of its owner class. As a result, static inner classes have no restrictions as to the location from which they could be instantiated.
In contrast, a non-static inner class has access to both static and non-static members of its owner class. To make this possible, Java compiler embeds a hidden pointer to the owner into the nested class, and passes an instance of the owner to that constructor.
This behavior relies on the availability of owner's this at the point of instantiation of the non-static inner class. If compiler were to allow you to inherit from a non-static member outside its owner, it wouldn't be able to instantiate your derived class, in effect forcing it to behave as if it were an inner class. That is why the compiler prohibits such inheritance.
This question already has answers here:
Overriding interface's variable?
(4 answers)
Closed 5 years ago.
Here we go with my question:
I have an interface with a static variable nr
public interface TestInterface {
public static int nr = 1;
}
And a class which implements that interface and has it's own static variable nr too.
public class TestClass implements TestInterface {
public static int nr = 2;
}
And I can actually do this without an error!
public static void main(String args[]) {
TestClass test = new TestClass();
System.out.println(TestClass.nr);
}`
Question: Why would this be allowed?
As far as I understand static fields should be universal through a class instances but what about the superclass - subclass relation?
It's explicitly allowed by the language.
If the class declares a field with a certain name,
then the declaration of that field is said to hide
any and all accessible declarations of fields with
the same name in superclasses, and
superinterfaces of the class.
http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3
In your code, both of the static fields are actually defined/meant for separate types i.e., one for TestInterface interface type and other for TestClass class type.
One point you need to understand is that, when it comes to static, there is no overriding, so they will be treated as separate fields.
In superclass - subclass relation the super class's static variables is shadowed by sub class's static variables if they have same name. Because the static variables aren't polymorphic.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
public class EnclosingClass{
public void enclosingClassMethod(){
InnerClass iC = new InnerClass();
ic.innerClassPrivateMethod(); // this one works but why the following line doesn't //work
InnerClass.innerClassPrivateMethod(); // Why I can't call the method like this?
}
public class InnerClass{
private void innerClassPrivateMethod(){
}
}
}
Why we can't call the innerClassPrivateMethod() like InnerClass.innerClassPrivateMethod()? I see "Cannot make a static reference to the non-static method innerClassPrivateMethod() from the type EnclosingClass"
If I change both the innerClassPrivateMethod and enclosingClassMethod as private I get error for
InnerClass iC = new InnerClass();
as "No enclosing instance of type Basics6 is accessible. Must qualify the allocation with an enclosing instance of type enclosingClass."
In case you want to call the method of inner class using class name or we can say statically then you need to do following changes.
Declare inner class method to be static.
A non static inner class can never have a static method So you need to change inner class to be static.
public class EnclosingClass{
public void enclosingClassMethod(){
InnerClass iC = new InnerClass();
iC.innerClassPrivateMethod(); // this one works but why the following line doesn't //work
InnerClass.innerClassPrivateMethod(); // This also works...
}
public static class InnerClass{ // Class converted to static
private static void innerClassPrivateMethod(){ // Method converted to static
}
}
}
If the method is not denoted static, it is an instance method. In this case the instance must be the inner class. Since you don't access the method through an instance in the second call, there is no this reference, etc.
Defining static methods in an inner class is quite useless. First of all is the "supporting class" of a static method arbitrary. I might add a public static void sort (int[] data); as well to a Utils class as to a ThisIsAUselessClass. The only reason why it matters is because you sometimes want to make such methods private. Now since a class can see all (inclusing private) members of its inner classes and inner classes have access to all the private methods of its "outer class", there is no reason to define a static method in an inner class.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a question about this topic:
An instance by a inner class need everytime an object of the same type of the guest class of the inner class. example:
public class GuestClass {
class innerClass {
}
public static void main(String[] args) {
innerClass test = new innerClass(); //does not work because
//I need a object of type GuestClass
GuestClass iNeedYou = new GuestClass();
innerClass nestClassObj = iNeedYou.new innerClass(); //it works
}
}
ok it's clear.
the innerClass object now points also to an GuestClass object (iNeedYou)
Now come my question:
an anonymous class is also a inner class right?
but with some difference:
A. I don't know the type of this object
B. it implements an interface.
but it is still an object by an inner class (anonymus but inner)
in fact if I do this:
public class GuestClass {
private int numb = 100;
class innerClass {
}
public void createAnAnonymusObject () {
myInterface myAnObj = new myInterface(){
int a, b;
#Override
public void print() {
System.out.println(numb); //it works
}};
myAnObj.print();
}
public static void main(String[] args) {
GuestClass iNeedYou = new GuestClass();
iNeedYou.createAnAnonymusObject();
}
}
works because the anonymous inner object points to the outer object... so i can see the variable numb.
but why this works?
public static void main(String[] args) {
myInterface myAnObj = new myInterface(){ //why does it work? in this case
//where is the outer object?
int a, b;
#Override
public void print() {
}};
}
if the anonymous class is an inner class why it doesn't need an outer object?
You're basically asking two questions here.
Why does a non-static nested class require an enclosing instance?
Because it's assumed to have access to all non-static members of the outer class. Even if you don't actually use any of those, the compiler can't infer that the non-static nested class can be used safely in static context. You have to explicitly mark it static to allow this.
Where and what is the enclosing object of the anonymous class created in this snippet?
public class OuterClass {
private int nonStaticMember;
private static int staticMember;
public static void main(String[] args) {
MyInterface myAnObj = new MyInterface(){ //why it works ?? in this case
//where is the outer object?
#Override
public void print() {
//nonStaticMember is not visible in this scope
//staticMember is visible in this scope
}};
}
}
In this case, your anonymous class has no enclosing instance. It's created in a static context, in the main method. You can instantiate MyInterface because all interfaces are implicitly static, even if defined inside another class. That's why the interface is visible at all. All of the non-static members of OuterClass, on the other hand, are not available in this scope so you're guaranteed not to use any of them. This is why there is no need to have a reference to an enclosing object. In fact, this is included in the language's specification.
Take a look at this Java Language Standard excerpt
Let C be the class being instantiated, and let i be the instance being
created. If C is an inner class then i may have an immediately
enclosing instance. The immediately enclosing instance of i (§8.1.3)
is determined as follows.
If C is an anonymous class, then:
If the class instance creation expression occurs in a static context
(§8.1.3), then i has no immediately enclosing instance.
Otherwise, the immediately enclosing instance of i is this.
(...)
I only quoted the most relevant part for this use case. Feel free to dive a little deeper into it.
public class Anonymous2 {
private int numb = 100;
public static void main(String[] args) {
MyInterface myAnObj = new MyInterface(){ //why it works ?? in this case
//where is the outer object?
int a, b;
#Override
public void print() {
System.out.println(numb);
}};
}
}
interface MyInterface {
public void print();
}
Compiling:
C:\JavaTools>javac Anonymous2.java
Anonymous2.java:11: error: non-static variable numb cannot be referenced from a static context
System.out.println(numb);
^
1 error
As can be seen, the code that the OP claimed would compile doesn't. So this entire question is irrelevant.
This question already has answers here:
Closed 14 years ago.
Duplicate: What does the 'static' keyword do in a class?
I've read this post already.
What does the "static" keyword in a method do?
I remember being told that static != clingy...but that is pretty much all I know about this keyword.
Static class variables can be thought of as a global class. No matter how many instances of the class you have, there is just one instance of each static variable.
Static methods don't use any non-static class variables and they can be called directly from outside of the class without having to instantiate the class itself.
Static variables and methods belong to the class and not instance, although you can refer them from an instance reference. Usually, you use the Class name to access them.
If a method is declared as static, you don't need the object's instance in which it is defined to invoke it. Now, you might want to know when could such a situation arise? Consider the main method of java
public static void main(String[] args)
Why is it declared static? It's because in order to start your program this method should begin execution. And, since the program hasn't initialized there is no way you could create an instance of the class in which it is declared. Therefore, you are required to declare the class as public. And, this static method gets called when the class is loaded in memory through
java YourClassName
Besides this, static methods are used to modify static variables. They cannot manipulate non-static instance variables.
Also, be aware, that static holds a different meaning in another language like C.
A static method belongs to the Class it is defined in and not to instances of objects of that Class, as non-static methods do. As a side-effect of not belonging to the instances of a Class, it's a compile error to try and access non-static fields in a static method. There's no "this" for the static methods to get access of the non-static fields from.
The Java Math class is a great example because it's loaded with static methods. You never create an instance of the Math class, you just call methods directly from the class.
Math.abs(3.14);
The value of a static variable within a method is stored between calls to that method
public void method() {
static int callCount = 0;
callCount++;
System.out.println("Calls: " + callCount);
}
method(); // "Calls: 1"
method(); // "Calls: 2"
method(); // "Calls: 3"
Note that this is completely different from a static method. A static method is called upon the class it is defined in instead of an instance of this class.
class MyClass {
public static void staticMethod() { ... }
public void nonStaticMethod();
}
Myclass.staticMethod();
MyClass instance = new MyClass();
instance.nonStaticMethod();
a static method is one that's established for the class. It doesn't need (and doesn't have) a this pointer, and can't access instance data. So you can write something ike
public class Hello {
void instanceHello() {
System,out.println("Hello from the instance.");
}
public static void main(int argc, String[] argv){
// The main method is defined even though there are no instances
System.out.println("Hello from main.");
instanceHello(); // but this is a syntax error;
Hello h = new Hello();
h.instanceHello(); // this isn't though
}
}