0

We have self registering subclasses of 'Handler' which we want to access through Subclass.me(). Is something similar to this possible in Java: ?

public class Handler{
static Vector<Handler> register=new Vector<Handler>();
public static Handler me() {
        return register.get( this.class);// TODO
}
}

public class SubClass extends Handler{
     SubClass(){register.add(this);}// OK
}

To clarify the question: Is it possible to retrieve the CLASS when calling a static java method? this.class obviously doesn't work, because 'this' is not available.

2 Answers 2

4

Static methods belong to the class. They cannot be overridden.

MyClass.myStaticMethod()

is the only correct way of accessing a static method.

Sign up to request clarification or add additional context in comments.

2 Comments

They don't need to be overwritten, but the second part answers the question. If MyClass.myStaticMethod() is the only correct way, how come calling Subclass.myStaticMethod() does not even give a warning in eclipse??
@Anno2001 Eclipse lets you choose if you want to get an error/warning or ignore non-static access to a static member. Look under Eclipse preferences, Java —> Compiler —> Errors/Warnings —> Code Style —> Non-static access to static member.
0

In java, you cannot make a static reference to the non-static method/variable. So,

  • If you want to access a non-static method / variable then you must create an instance of the class first.
  • If you are going to access a static method / variable then you can access it directly through the class name without creating a instance.

Because, the static method and variable are belong to the Class not to the Instance while the non-static method and variable are belong to the Instance not to the Class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.