Accessing class in static java method - java

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.

Static methods belong to the class. They cannot be overridden.
MyClass.myStaticMethod()
is the only correct way of accessing a static method.

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.

Related

Is there something called Local Static Inner Class?

i was just experimenting with inner classes and came across this idea of having local yet static inner class... well i made an inner class inside a static method.. well it's just simple as that..
Here's the example i did
class Outer {
static void m() {
class LocalStatic {
void s() {
System.out.println("static local inner class method");
}
}
}
}
class Demo {
public static void main(String args[]) {
Outer.m();
}
}
This doesn't give any compile error.
I know how to access the static method m. But i want to know if there's a way to access the local class LocalStatic from an outside class.. Well as to my understanding, we can't access something inside a method right? Hence i can't access either LocalStatic or any methods or attributes inside that local class from outside of the class Outer Just wanted to make sure..
I want to know if there's a way to access the local class LocalStatic from an outside class
There isn't a way to do that. Local classes are, well, local, so the only way to access them is from the method in which the class is in scope*.
You can access objects of a local class using non-local base class or an interface:
interface SomeInterface {
void s();
}
class Outer {
static SomeInterface m() {
class LocalStatic implements SomeInterface {
public void s() {
System.out.println("static local inner class method");
}
}
return new LocalStatic();
}
}
Now you can write
SomeInterface i = Outer.m();
i.s();
Demo.
* It goes without saying that there is also a way to access these classes through reflection, but that is outside capabilities of Java language itself.
"Hence i can't access either LocalStatic or any methods or attributes inside that local class from outside of the class Outer Just wanted to make sure.." The scope is even smaller than Outer class - you can access LocalStatic class only in m() method.
The answer to the question in your title is that you can declare a local inner class in a static context (static method or static initializer) but then it won't have an enclosing class instance. So it makes some sense to call it
Local Static Inner Class
or maybe
Local static nested class
I have never seen anyone call them that or in fact use them.
You can declare a class inside any method or constructor or initializer. Such a class is called a local class. Whether the method is static or not is not relevant. It is not possible to refer to such a class from any part of the code other than the method or constructor or initializer it is declared in.
Local classes are almost never used. I have known people who have been professional java programmers for years who were not aware that classes could be declared inside methods.

Use of this and super within local classes defined in a static context

I was going through the following code while studying Java local classes :-
class A {
protected int one;
}
class Outer {
static void staticMethod(){
class InnerLocal extends A {
double first = this.one;
double second = super.one;
}
}
}
My doubt is that when we declare the local classes inner to static method or static initializer block then they implicitly work as static member classes as they need no outer class to instantiate them. However I know the difference clearly between a static member class and static local class(i.e. the inner class defined in static block), the problem is that Java does not allows the object references 'this' and 'super' to be used in static context but the code above compiles perfectly.
Can anyone please provide me the reason why Java compiler doesn't complains on using 'this' and 'super' in static context in the above case? Thanks!:)
My doubt is that when we declare the local classes inner to static method or static initializer block then they implicitly work as static member classes as they need no outer class to instantiate them
This is the root cause of your confusion. Just because a method is static does not mean that anything declared within the method is also static. If you declare a variable (say int a) inside a static method, it is said to be a local variable. It would make no sense to say that a is a method local static variable. Similarly, it would make no sense to say that InnerLocal is a method local static class. (There is no such thing as static local variable in Java)
InnerLocal is therefore a regular class that extends from A and inherits the a member variable from A and is able to access it either through this or through super. It would also help to know that final is the only non-access modifier that can be used within a method in Java.
Java does not allows the object references this and super to be used in static context but the code above compiles perfectly.
static as in "static class" is not the same as static as in "static context".
All instance methods and constructors have access to this and super. Since constructors have access to this and super, initializers of instance fields have access to this and super as well. A static inner class has no outer instance, but it has its own instance. That is what this refers to.
In contrast, static methods have no access to this and super, regardless of the class in which these static methods are defined (top-level, static inner, non-static inner, anonymous, etc.)

Call a non-static method in main static method in Java

So I am calling a method defined in the main method of the same class. I am referencing the callable method using 'this' keyword. Why cannot I call this non-static method, as shown below, in static main method?
Relevant but a little different question, by choice of design, would it make sense to construct a separate class for implementing logic. Essentially, main class should only have a main method to keep things simple. Any ideas will be appreciated.
UniqueChars.java:8: non-static variable this cannot be referenced from a static context
System.out.println(this.hasAllUniqueChars(input));
^
1 error
public class UniqueChars {
boolean hasAllUniqueChars(String input) {
return false;
}
public static void main(String[] args) {
String input = "Harry";
System.out.println(this.hasAllUniqueChars(input));
}
}
Because this is non-static. this is an instance, and you cannot reference instance variables within a static method since static means "one for the entire class."
You should make the hasAllUniqueChars method static (like static boolean hasAllUniqueChars(String input)), so you could do
System.out.println(UniqueChars.hasAllUniqueChars(input));
Or just (since you're already in the class)
System.out.println(hasAllUniqueChars(input));
You could also keep it non-static, and do this:
UniqueChars uc = new UniqueChars();
System.out.println(uc.hasAllUniqueChars(input));
You can only use "this" within an instance of an object.
So you either need to make a UniqueChars object, or you need to make hasAllUniqueChars static
Because there's no this in a static method, because this refers to the current instance (e.g., an instantiated object of that class).
There's no instance for static methods: that's why they're called static methods. They live at the class level, and are not associated with any instance.
You should either (a) create an instance and call the instance method on it, or (b) make the method static and don't bother. If the class doesn't need any instance-specific state, might as well make it static, e.g., a utility method.
Use this code:
System.out.println(new UniqueChars().hasAllUniqueChars(input));
Method hasAllUniqueChars is not static. To make it static you have to put static before name boolean like static boolean hasAllUniqueChars. Static methods don't need instances to be able to call them. So you would call it as UniqueChars.hasAllUniqueChars().
if you don't want method to be static then you would need to create new instance of UniqueChars class and then call it. new UniqueChars().hasAllUniqueChars() as others have pointed out.
Either construct an instance of the class that has the main method (possibly in main() itself), and invoke the method on it.
System.out.println(new UniqueChars().hasAllUniqueChars(input));
Or make hasAllUniqueChars() a static method.
Within an instance method or a constructor, this is a reference to the current object, which is non-static. You can't use non-static instance to static method.

Java: When is the variable "this" initialized?

public class MainMDI extends javax.swing.JFrame {
private static MainMDI thiz;
public MainMDI() {
initComponents();
thiz = this;
}
}
I'm creating an MDI application in swing. Class MainMDI is the main class of the application and therefore the main method resides in that class. The above code creates a static variable called thiz that points to the instance of class MainMDI when the application runs.
I'm planning to use variable thiz to access non-static (instance) members of class MainMDI from within the main method.(I cannot access non-static members from from within the main method since the main method is a static member in class MainMDI in my application).
public class MainMDI extends javax.swing.JFrame {
private static MainMDI thiz = this;
public MainMDI() {
initComponents();
}
}
But when I attempt to initialize variable thiz as in the above code, compiler says non-static variable this cannot be referenced from a static context. But I'm not referring to this in a static context here am I? Is this because variable this, being non-static, is not yet initialized when the static variable this is initialized?
Also, would it have been a better programming practice if I had not set class MainMDI as the main class and created another class with a main method in it and set that class as the main class?
But when I attempt to initialize variable thiz as in the above code,
compiler says non-static variable this cannot be referenced from a
static context. But I'm not referring to this in a static context here
am I?
Yes, you are. Static class variables are initialized when the class is loaded (not when an object instance is being created). There is no this in that context. The code:
private static javax.swing.JFrame thiz = this;
Will simply not work. Despite your assertions to the contrary, you do want a singleton. Otherwise, given N possible object instances of your MainMDI object, which one would you be expecting to access from a static context? You should consider refactoring your code rather than trying to strong-arm around Java language semantics.
this means "the object instance currently being operated on", it only makes sense inside a non-static member function. In general this is implicitly passes to each non-static member function when you call that member function so it'd be fair to say that it is initialized right before a non-static member function gets called.
Whether factoring out a class with "main" method is a good idea will heavily depend on actual implementation details.

java objects, shared variables

I have a simple question here.
If I declare a variable inside an object which was made [declared] in the main class, like this:
public static int number;
(
usually I declare it like this :
private int number;
)
can it be used in a different object which was also made [declared] in the main class?
btw I do not care about security atm, I just want to make something work, don't care about protection)
Here's a telling quote from Java Language Specification:
JLS 8.3.1.1 static Fields
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized.
A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
[Example program follows...]
In short, a static field is a class variable: it belongs to the class, as opposed to the instances of the class. In a way, you can think of a static field as a variable shared by instances of the class, but it's much more consistent to think of static fields as belonging to the class, just like static method also belongs to the class, etc.
Since they belong to the class, they do not require an instance of said class to access (assuming adequate visibility), and in fact it's considered bad programming practice to access static members through an instance instead of a type expression.
Related questions
Java - static methods best practices
Static methods
calling non-static method in static method in Java
non-static variable cannot be referenced from a static context (java)
When NOT to use the static keyword in Java?
Static variables and methods
If the class holding 'number' is called MyClass
you can refer to it as MyClass.number from any method.
Doing so for a variable is not good design though.
There are really two issues here: public vs. private in the context of inner classes, and static variables.
Part 1:
static means that you don't need an instance of the class to access that variable. Suppose you have some code like:
class MyClass {
public static String message = "Hello, World!";
}
You can access the property this way:
System.out.println(MyClass.message);
If you remove the static keyword, you would instead do:
System.out.println(new MyClass().message);
You are accessing the property in the context of an instance, which is a copy of the class created by the new keyword.
Part 2:
If you define two classes in the same java file, one of them must be an inner class. An inner class can have a static keyword, just like a property. If static, it can be used separately. If not-static, it can only be used in the context of a class instance.
Ex:
class MyClass {
public static class InnerClass {
}
}
Then you can do:
new MyClass.InnerClass();
Without the 'static', you would need:
new MyClass().new InnerClass(); //I think
If an inner class is static, it can only access static properties from the outer class. If the inner class is non-static, it can access any property. An inner class doesn't respect the rules of public, protected, or private. So the following is legal:
class MyClass {
private String message;
private class InnerClass {
public InnerClass() {
System.out.println(message);
}
}
}
If the inner class has keyword static, this would not work, since message is not static.
static variables are shared by all instances of a given class. If it's public, it is visible to everything.
non-static variables belong to only one instance.
Since your main method is static, it can only see static variables. But you should avoid working statically - make an instance of a class, and pass the data around as method/constructor parameters, rather than sharing it via static variables.

Categories

Resources